1

I have a django model DateTimeField with auto_now=True and auto_now_add=True for created and updated. When I save the model, both fields saves as None. Anyone know what's causing this?

The model:

class Referral(models.Model):
    ..
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    ..

It has custom save method:

def save(self, *args, **kwargs):
        #TODO: fix the created and updated field that is not working now
        if not self.id:
            code_settled = False
            while not code_settled:
                referral_code = self._generate_referral_code()
                try:
                    r = Referral.objects.get(referral_code=referral_code)
                except:
                    self.referral_code = referral_code
                    code_settled = True

            self.expiry_date = self.reward_program.expiry_date
            if self.referrer.user.profile.cellphone_verified:
                self.referrer_reward_status = 'F'
            else:
                self.referrer_reward_status = 'C'

            if self.referee.profile.cellphone_verified:
                self.referee_reward_status = 'F'
            else:
                self.referee_reward_status = 'C'
        else:
            self._referral_code = self.referral_code

        super(Referral, self).save(*args, **kwargs)

How I create the Referral:

referral = Referral(referrer=referrer, referee=user, reward_program=self, _referral_code='stub')
referral.save()

auto_now works in my other models in my code base. I tried commenting out the custom save method to see if it's causing the problem, but apparently it's not. I know there are alternative solutions already to fix this, but I am very curious what is causing this inconsistency.

Dawin Widjaja
  • 61
  • 4
  • 12
  • See this link http://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add – GThamizh Mar 09 '16 at 05:50
  • @GThamizh appreciate the reply, but I have seen this link already. I see so far no one can explain this phenomenon yet :) – Dawin Widjaja Mar 09 '16 at 07:01
  • Make a BaseModel class and add these(datetime) fields in it. And inherit BaseModel in your own Models, for BaseModel class make a Meta Class and `abstract = True` for BaseModel class. – Usman Maqbool Mar 09 '16 at 07:32
  • update to the problem: I tried implementing the solution mentioned in http://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add, but turns out it doesn't work as well, i.e. when I see my mySQL DB, I can see something like: 2016-03-10 05:26:33.000000 on the updated DateTimeField, but in django admin and front-end, it still shows as None – Dawin Widjaja Mar 10 '16 at 06:27

0 Answers0