Django - 在模型字段中一起空白

时间:2021-07-05 19:24:17

How to do something like this:

怎么做这样的事情:

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

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

EDIT: This is similar to unique_together. When a field is filled, the user has to fill both.

编辑:这类似于unique_together。填充字段时,用户必须填写两者。

2 个解决方案

#1


1  

You can try, save method;

你可以尝试,保存方法;

   def save(self,*args, **kwargs):
      if self.name == '' or self.alt_name == '':
         self.name = ''
         self.alt_name = ''
      super(Example, self).save(*args, **kwargs)

#2


0  

Below is an implementation of a mixin that accomplishes this.

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

# 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')

If you are interested in learning more about mixins I highly recommend Two Scoops of Django's take on the subject.

如果您有兴趣了解有关mixins的更多信息,我强烈推荐Django的两个Scoops对此主题的看法。

#1


1  

You can try, save method;

你可以尝试,保存方法;

   def save(self,*args, **kwargs):
      if self.name == '' or self.alt_name == '':
         self.name = ''
         self.alt_name = ''
      super(Example, self).save(*args, **kwargs)

#2


0  

Below is an implementation of a mixin that accomplishes this.

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

# 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')

If you are interested in learning more about mixins I highly recommend Two Scoops of Django's take on the subject.

如果您有兴趣了解有关mixins的更多信息,我强烈推荐Django的两个Scoops对此主题的看法。