views:

36

answers:

3

Hi.

I get a model object, change an attribute, save it and it still has the old attribute:

>>> g = SiteProfile.objects.get(pk=3)
>>> g.renew_date
datetime.date(2010, 4, 11)
>>> g.renew_date = date.today()+timedelta(days=365)
>>> g.renew_date
datetime.date(2011, 4, 11)
>>> g.save()
>>> g.renew_date
datetime.datetime(2010, 4, 11, 16, 57, 4, 192684)

Anyone know if this is an issue with the database or something else?

A: 

Please check the django document for the automatic commit. I guess you have to enable the automatic commit to accept the change immediately.

sza
A: 

Maybe you have set DISABLE_TRANSACTION_MANAGEMENT to False:

As the Django says:

If you do this, Django won't provide any automatic transaction management whatsoever. Middleware will no longer implicitly commit transactions, and you'll need to roll management yourself. This even requires you to commit changes done by middleware somewhere else.

Satoru.Logic
+2  A: 

I figured it out.

The issue was that the field renew_date had the argument auto_now set to True as such:

renew_date = models.DateField(auto_now=True, editable=False)

I understood auto_now to mean that the current date will be used when creating the object, but it turns out that's not the case:

DateField.auto_now

Automatically set the field to now every time the object is saved. Useful for "last-modified" timestamps. Note that the current date is always used; it's not just a default value that you can override.

From django docs.

What I needed was auto_now_add which:

Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it's not just a default value that you can override.

So, after changing my renew_date field:

renew_date = models.DateField(auto_now_add=True, editable=False)

it all works, just fine :)

>>> g = SelectStatProfile.objects.get(pk=3)
>>> g.renew_date
datetime.date(2010, 4, 11)
>>> from datetime import date, timedelta
>>> g.renew_date = date.today()+timedelta(days=365)
>>> g.renew_date
datetime.date(2011, 4, 11)
>>> g.save()
>>> g.renew_date
datetime.date(2011, 4, 11)
Pilgrim