简体   繁体   中英

How to unite together 2 model fields in Django?

I have 2 fields in my model class

class A(model.Model):
    field1 = models.ImageField(upload_to='path', null=True)
    field2 = models.URLField(null=True)

I need to unite so that if first field is full, second field can't be filled. And vice versa.

I try to create Meta class in class A with field unique_together:

class Meta:
    unique_together = (field1, field2)

but in that case, both field can't be empty and both can be full. But I need that just 1 of fields must be full.

Customize save() method in you A model:

def save(self, *args, **kwargs):
    if not self.field1:
        self.field2 = ...
    if not self.field2:
        self.field1 = ...    
    super(A,self).save(*args,**kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM