[英]Django Admin one field required related on other field
我正在使用 Django admin 來保存模型,我的模型如下所示:
class PurchaseItem(models.Model):
product=models.ForeignKey("products.Product",on_delete=models.CASCADE,blank=True,null=True)
product_attribute=models.ForeignKey("products.ProductAttribute",on_delete=models.CASCADE,blank=True,null=True)
目標是只保存一個外鍵,例如:
我會向該模型添加一個clean()
方法。 這種方法可以實現為:
class PurchaseItem(models.Model):
...
def clean(self):
if self.product is None and self.product_attribute is not None:
raise ValidationError("Can not set both product and product attribute")
if self.product is not None and self.product_attribute is None:
raise ValidationError("Can not set both product attribute and product")
if self.product is None and self.product_attribute is None:
raise ValidationError("Either product or product attribute must be set")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.