我需要选择其中一个,但两者都不能为空。有可能吗?
location = models.ForeignKey('Location', help_text="Enter inventory location", null=True, blank=True)
assigned = models.ForeignKey(User, blank=True, null=True)
答案 0 :(得分:2)
您可以使用clean()
方法验证模型。如果模型无效,则可能引发验证错误:
def clean(self):
if not self.location and not self.assigned:
raise ValidationError('Either location or assigned should be non-blank')
有关clean方法的更多信息,请参阅Django文档:
https://docs.djangoproject.com/en/1.7/ref/models/instances/#django.db.models.Model.clean
答案 1 :(得分:0)
您可以在模型中覆盖save
方法来处理此
def save(self, *args, **kwargs):
if not self.location and not self.assigned:
# Warn the user about the issue
else:
super(<your_model_name>, self).save(*args, **kwargs)