开发者

How to overwrite auto_now_add in django model

I have a model that is roughly开发者_如何学Python:

class Day(models.Model):
    info = models.ForeignKey("Info")
    date = models.DateField(auto_now_add=True editable=True)
    data = models.IntegerField()

But I want to initialize the model with a script inserting data for yesterday. The script calls a series of json's and parses data from them roughly:

for info in infos:
    init = Day(info=info, date=datetime.date.today()+datetime.timedelta(-1), data=0)
    init.save()

I read in this question about the idea of setting the model to something like auto_now_add= not initialize so that auto_now_add will be false when running the initialize script but couldn't figure out how to connect the initialize variable to the script.

Can anyone explain to me how to overwrite the auto_now_add field either through this or another way. I would prefer now to add another model if it is possible.


class TimeDeltaDateField(models.DateField):
    def __init__(self, verbose_name = None, name = None, time_delta, *args, **kwargs):
        self.time_delta = time_delta
        super(models.DateField, self).__init__(verbose_name, name, *args, **kwargs)

    def pre_save(self, model_instance, add):
        if self.auto_now or (self.auto_now_add and add):
            value = datetime.datetime.now() + self.time_delta
            setattr(model_instance, self.attname, value)
            return value
        else:
            return super(models.DateField, self).pre_save(model_instance, add)

try this field and usage is here:

  TimeDeltaNewDateField(time_delta = datetime.timedelta(-1), auto_now_add = True)


Save it, so the auto_now gets set. Then you set the field, and then save it again.

I think...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜