Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to insert sql statements into sqlite3 database and configure with models

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.

like image 775
Joe Avatar asked Oct 24 '25 11:10

Joe


1 Answers

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

like image 90
doniyor Avatar answered Oct 27 '25 02:10

doniyor