Thursday, June 29, 2017

Pre-loading static data into database table

Reading
<https://docs.djangoproject.com/en/1.11/ref/migration-operations/#django.db.migrations.operations.RunSQL>
tells me that runSQL allows arbitrary SQL to run on the database ... except
for the postgres backend: "On most database backends (all but PostgreSQL),
Django will split the SQL into individual statements prior to executing
them."

I want to insert data into the two columns of the database. The model
reads:

class Cities (models.Model):
city_name=models.CharField(max_length=24, unique=True)
county_name=models.CharField(max_length=12, unique=True)

and I have a list of 419 pairs of names I want to pre-load into this
database table. The rows contain the two variables; e.g.,
Bend,Deschutes
Birkenfeld,Columbia
Blachly,Lane
Black Butte Ranch,Deschutes

So, using a postgres back end can I write,

migrations.RunSQL("INSERT INTO Cities (city_name,county_name) VALUES
('Bend','Dechutes');")

repeated for each row in the table (easy to do with emacs)? And, can I put
this code in models.py after the classes?

Rich

No comments:

Post a Comment