2016-06-23 77 views
2

我需要获取每个类,它继承了models.Model以创建和更新字段。我可以通过为每个字段添加自定义保存方法来实现此目的,但这违反了Don'tRepeatYourself规则。覆盖模型中的每个类的保存方法。模型

我试图重写models.Model:

class LogModel(models.Model): 
    created = models.DateTimeField(editable=False) 
    updated = models.DateTimeField() 

    def save(self, *args, **kwargs): 
     if not self.id: 
      self.created = timezone.now() 
     self.updated = timezone.now() 
     return super(LogModel, self).save(*args, **kwargs) 

,并使用LogModel代替models.Model,但这种失败,错误E006( 字段 'X' 的冲突与现场的 'X'从模式“y.logmodel”。

编辑

我的主要问题是如何将自定义特定领域在我的models.py添加到所有型号

+2

请确保您的缩进的问题,正确显示,这样你就不会在错误的事情得到反馈。 (对Python尤其重要。)另外,请详细说明“没有工作”的含义。你试过的时候究竟发生了什么?它没有保存过吗?它默默地失败了吗?它是否抛出异常? –

回答

4

你的基础模型必须是抽象:

class LogModel(models.Model): 

    class Meta: 
     abstract = True 

    created = models.DateTimeField(editable=False) 
    updated = models.DateTimeField() 

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None): 
     # Use self._state.adding to check if this is a new instance, 
     # ID not being empty is not a guarantee that the instance 
     # exists in the database 
     # and if `update_fields` is passed, you must add the fields to the 
     # list or they won't be saved in the database. 
     if force_insert or self._state.adding: 
      self.created = timezone.now() 
      if update_fields and 'created' not in update_fields: 
       update_fields.append('created') 
     self.updated = timezone.now() 
     if update_fields and 'updated' not in update_fields: 
      update_fields.append('updated') 
     return super(LogModel, self).save(*args, **kwargs) 

但是,如果重写save()方法,这意味着它不会以任何形式进行编辑。如果这是你想要的东西,那么你最好使用auto_nowauto_now_add

class LogModel(models.Model): 

    class Meta: 
     abstract = True 

    created = models.DateTimeField(auto_now_add=True) 
    updated = models.DateTimeField(auto_now=True) 
0

而是覆盖保存方法,你可以定义auto_now_addauto_now参数示范场,如:

created = models.DateTimeField(auto_now_add=True) 
updated = models.DateTimeField(auto_now=True) 

有关这些参数的更多信息,你可以检查django docs

+0

我的主要问题是如何向所有模型添加特定字段。 –

+0

可以通过定义[抽象模型](https://docs.djangoproject.com/en/1.9/topics/db/models/#abstract-base-classes)并在其中定义保存方法并创建所有模型从抽象类继承。 –

+0

谢谢。答案很简单。 –

0

它可以通过定义Abstract Base Model来完成,并确定保存方法有通过从抽象类继承创建的所有车型。例如从它

class MyAbstractModel(models.Model): 
    created = models.DateTimeField(editable=False) 
    updated = models.DateTimeField() 

    def save(self, *args, **kwargs): 
     if self._state.adding: 
      self.created = timezone.now() 
     self.updated = timezone.now() 
     return super(LogModel, self).save(*args, **kwargs) 

    class Meta: 
     abstract = True 

,并创建子模型类:

class Record(MyAbstractModel): 
    pass