1

如何做这样的事情:

class Example(models.Model):
    name = models.CharField(max_length=255)
    alt_name = models.TextField()

    class Meta:
        blank_together = ('name', 'alt_name') #?!

编辑:这类似于unique_together. 当一个字段被填写时,用户必须同时填写。

4

2 回答 2

2

下面是mixin实现这一点的 a 的实现。

# your_app/mixins.py

class BlankAble(models.Model):
    # when creating the BlankAble class object it will add a __blank_together__ 
    # attribute corresponding to the same in {YourModel}.MyMeta.blank_together
    def __new__(cls, *args, **kwargs):
        new = super().__new__(cls)
        if hasattr(cls, 'MyMeta'):
            if hasattr(cls.MyMeta, 'blank_together'):
                setattr(new, '__blank_together__', cls.MyMeta.blank_together)
        return new


    def save(self, *args, **kwargs):
        # returns False if any but not all of the __blank_together__ fields 
        # are not blank
        blank_together = not (any([getattr(self, field, None) for field in getattr(self, '__blank_together__', None)]) and \
                              not all([getattr(self, field, None) for field in getattr(self, '__blank_together__', None)]))
        if not blank_together:
            raise ValidationError(f"{getattr(self, '__blank_together__', None)} must all be blank together.")
        return super().save(*args, **kwargs)


    class Meta:
        # prevents Django from having some bad behavior surrounding
        # inheritance of models that are not explicitly abstract
        abstract = True

# your_app/models.py    

class TestModel(BlankAble, models.Model):

    test_field1 = models.CharField(blank=True, null=True, max_length=25)
    test_field2 = models.CharField(blank=True, null=True, max_length=25)
    test_field3 = models.CharField(blank=True, null=True, max_length=25)

    class MyMeta:
        blank_together = ('test_field1', 'test_field2')

如果您有兴趣了解更多关于mixins该主题的信息,我强烈推荐 Django 的两个独家新闻。

于 2018-04-26T15:11:55.437 回答
1

你可以试试,保存方法;

   def save(self,*args, **kwargs):
      if self.name == '' or self.alt_name == '':
         self.name = ''
         self.alt_name = ''
      super(Example, self).save(*args, **kwargs)
于 2012-11-05T07:46:51.700 回答