4

I'm using Django for a project. I have a .sql file containing insert statements. How can I get them into my sqlite3 database and have them work with my models?

The project "fortune" has a models.py file that looks like the following:

class fortune(models.Model):
  id = models.IntegerField(primary_key=True)
  category = models.CharField(max_length=50)
  length = models.IntegerField()
  aphorism = models.CharField(max_length=5000)

I have a .sql file with a list of Insert statements like the follwing:

INSERT INTO "fortune_fortune" VALUES(1,'fortunes',127,'Arbitrary Text');

When I run .schema on my db.sqlite3 file which is configured with my project I see:

CREATE TABLE fortune_fortune(id integer, category varchar(50), length integer, aphorism varchar(5000));

I've tried using .read in my sqlite shell with no luck. I've tried typing "sqlite3 file.sqlite3 < file.sql" in bash as well. There is something I'm missing here, but I can't seem to ID the problem.

Thanks for your help.

1 Answer 1

4

ok, wait.. normally you dont use sql statements to insert data into db, if you work with django.

to insert data into db, you work with django ORM which is way much fun than these ugly sql statements.

fortune = fortune(category='new cat', length=19, aphorism='i love life')
fortune.save()

then as a result, you will have one new row in fortune table in your db. just read django docs and you feel happy!

and one more thing, class names are always in capital.

to your issue:

Django provides a hook for passing the database arbitrary SQL that’s executed just after the CREATE TABLE statements when you run migrate. You can use this hook to populate default records, or you could also create SQL functions, views, triggers, etc.

The hook is simple: Django just looks for a file called sql/<modelname>.sql, in your app directory, where <modelname> is the model’s name in lowercase.

more in docs

Sign up to request clarification or add additional context in comments.

4 Comments

The problem is I have about 1500 of such insert statements in a file. I can't add them all by hand.
@Joe yeah, i just updated my answer. you can load your sql files
This hook feature was exactly what I was missing. I knew it had to exist in there somewhere. Thanks for pointing out what I seemed to overlook when searching docs!
@Joe my pleasure. glad i could help and feel free to ask if you need help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.