Reputation: 546
I am new with databases so maybe my thinking is flawed, but I would like to define a table with fixed entries (=initial data) using Django for a webapp. These entries would be defined once, remain unchanged, and should be present locally and to collaborators when they pull the code. I thought it would make it easier in the development period, where I have to set up the whole database from scratch several times, that some initial data is populated automatically from models.py. Is there a way in models.py to already populate the table with these entries?
class Field(models.Model):
name = models.CharField(max_length=200)
created_timestamp = models.DateTimeField(auto_now_add=True)
Upvotes: 0
Views: 237
Reputation: 598
A class is just a blue print, according to which actual instances will be created.
You probably have two options: 1. You can populate entries via create() or save() method in code. You should have default values in your class anyway, so then just creating an instance with
model.objects.create();
will automatically populate your db with an instance with your default values.
Upvotes: 1
Reputation: 12012
The term used is initial data, as already pointed out in the first comment, and not fixed data.
Once your app is in production the entries from the initial data can be edited or deleted, in case you provide appropriate actions as part of your business logic.
It is very important to mention, that if you provide your initial data as fixtures (JSON, YML, etc.) with the command:
python manage.py loaddata path/to/your/data
the model method save
won't be called. Also you have this field:
created_timestamp = models.DateTimeField(auto_now_add=True)
which won't be autopopulated. That means, if you provide data for your class Field
you have to supply the value for the above field:
Your fixtures could look somtething like this:
[
{
"model": "app_label.field",
"pk": 1,
"fields": {
"name": "foo",
"created_timestamp": "2018-03-12 12:00:00"
}
},
# further entries
]
You may omit the primary key ("pk"), if it is an auto field. Then it will be automatically populated by the database system.
If you create a directory fixtures
within your app directory, then you can load that fixture just by calling its name. Let's say you have this structure:
- project
- manage.py
- yourapp
- admin.py
- models.py
- fixtures
field.json
Then you could do:
python manage.py loaddata field
Upvotes: 1