如何为所有模型添加相同的保存方法

时间:2015-10-07 02:20:01

标签: python mysql django django-models

我有以下型号:

class Series(models.Model):
    item_id = models.CharField(max_length=60, unique=True, blank=True)
    name = models.CharField(max_length=600, blank=True)

    def save(self, *args, **kwargs):
        super(self.__class__, self).save(*args, **kwargs)
        if not self.item_id:
            self.item_id = '%s%s' % (self.__class__.__name__[0], self.pk)
            self.save()

我已经创建了这个通用的保存方法,我也想将其应用到其他模型中。我如何在models.py文件中执行此操作?

1 个答案:

答案 0 :(得分:1)

2个选项(两者都非常相似,它们以微妙的方式变化):

  1. 创建父类:

    class MyModel(models.Model):
        """My Custom Model Class"""
        def save(self, *args, **kwargs):
            super(self.__class__, self).save(*args, **kwargs)
            if not self.item_id:
                self.item_id = '%s%s' % (self.__class__.__name__[0], self.pk)
                self.save()
        # Must make the parent Model abstract to avoid table creation
        class Meta:
            abstract = True
    
    class Series(MyModel):
        item_id = models.CharField(max_length=60, unique=True, blank=True)
        name = models.CharField(max_length=600, blank=True)
    
  2. 创建一个Mixin

    class MySaveMixin(object):
        """My Mixin for providing save functionality to Models"""
        def save(self, *args, **kwargs):
            super(self.__class__, self).save(*args, **kwargs)
            if not self.item_id:
                self.item_id = '%s%s' % (self.__class__.__name__[0], self.pk)
                self.save()
    
    class Series(models.Model, MySaveMixin):
        item_id = models.CharField(max_length=60, unique=True, blank=True)
        name = models.CharField(max_length=600, blank=True)