Reputation: 21
suppose I have a Django object of this type:
class Some(Model):
some_value = CharField(max_length=20)
and after a while (and a few objects later) I understood I'd like to save the created time for each new object, so I add the following field:
created = FloatField(default=time.time)
Let's suppose now I have a few old object which were created without the "created" field. When I query them, they receive the default time.time, even though it's suppose to be None. How can I get a different value for all the old objects? I only want new objects to be created with this default, and say all old objects without this field to be None, or some other known value. Setting null=True doesn't make a difference.
Thanks!
Upvotes: 2
Views: 3074
Reputation: 6536
If I understand your question correctly, you want to add a created
field defaulted to now but want to set it to None
for old rows. You could achive this by making two migrations:
Add new field and default it to None
created = FloatField(null=True, default=None)
Run makemigrations
Change default value for newer fields:
created = FloatField(null=True, default=time.time)
Run makemigrations
Run migrate
When first migration run, all old rows created
will be set to None
(because they don't have a value and default will be used). When seconds migration run old rows will not change because they already has a value. New rows will use the default (time.time
).
syncdb
does nothing if table is already created in DB. You should modify your DB manually (i.e. ALTER TABLE
commands of SQL)
created
field with NULL
as default value.default=time.time
)When you add a new nullable column to DB, all existing rows will set to NULL
and Django handles default in application level.
Upvotes: 4