如何将 Django 中的 2 个模型字段联合在一起?
How to unite together 2 model fields in Django?
我的模型中有 2 个字段 class
class A(model.Model):
field1 = models.ImageField(upload_to='path', null=True)
field2 = models.URLField(null=True)
我需要团结起来,如果第一个字段已满,第二个字段就无法填充。反之亦然。
我尝试在 class A 中使用字段 unique_together:
创建 Meta class
class Meta:
unique_together = (field1, field2)
但在那种情况下,两个字段都不能为空,都可以为满。但我需要只有 1 个字段必须是完整的。
在你的模型中自定义 save() 方法:
def save(self, *args, **kwargs):
if not self.field1:
self.field2 = ...
if not self.field2:
self.field1 = ...
super(A,self).save(*args,**kwargs)
我的模型中有 2 个字段 class
class A(model.Model):
field1 = models.ImageField(upload_to='path', null=True)
field2 = models.URLField(null=True)
我需要团结起来,如果第一个字段已满,第二个字段就无法填充。反之亦然。
我尝试在 class A 中使用字段 unique_together:
创建 Meta classclass Meta:
unique_together = (field1, field2)
但在那种情况下,两个字段都不能为空,都可以为满。但我需要只有 1 个字段必须是完整的。
在你的模型中自定义 save() 方法:
def save(self, *args, **kwargs):
if not self.field1:
self.field2 = ...
if not self.field2:
self.field1 = ...
super(A,self).save(*args,**kwargs)