Reputation: 1121
I want to automatically load predefined data into a database table when python manage.py makemigrations is run
For example if I have a model
class Test(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=2)
value = models.IntegerField(default=0)
def __str__(self):
return str(self.name)
I want this database table to populate itself with following data on creation (when python manage.py makemigrations & python manage.py migrate is run)
id|name|value|
--------------
1 | AA | 0 |
2 | AB | 0 |
3 | AC | 0 |
4 | AD | 0 |
5 | AE | 0 |
6 | AF | 0 |
7 | AG | 0 |
8 | AH | 0 |
9 | AI | 0 |
10| AJ | 0 |
11| AK | 0 |
. | | |
. | | |
. | | |
xx| ZZ | 0 |
--------------
Upvotes: 0
Views: 1423
Reputation: 1762
You can do it with fixtures.
First, you don't need this id
field, by default, Django gives each model exactly this field id = models.AutoField(primary_key=True)
class Test(models.Model):
name = models.CharField(max_length=2)
value = models.IntegerField(default=0)
def __str__(self):
return str(self.name)
Then go to your app and create a fixtures
directory.
I create this code to generate your fixture:
from itertools import product
import json
def generate_fixture():
char_pairs = list(product(map(chr, range(97, 123)), repeat=2))
data = []
for i in range(0, len(char_pairs)):
data.append(
{
"model": "yourappname.test", # change yourappname
"pk": i+1,
"fields": {"name": ''.join(char_pairs[i]), "value": 0}
},
)
file = open('filename.json', 'w') # change filename
file.write(json.dumps(data, indent=2))
file.close()
if __name__ == "__main__":
generate_fixture()
change yourappname
and filename
before run this code.
The result is a json with 676 objects from aa
to zz
using the following structure:
[
{
"model": "yourappname.test",
"pk": 1,
"fields": {
"name": "AA",
"value": 0
}
},
]
Finally, copy and paste the json file inside yourapp/fixtures and run python manage.py loaddata jsonfilename
With json inside the fixture folder, if you clean the database, just run the loaddata command again.
Django - Providing data with fixtures
Upvotes: 4