我正在使用 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)
目標是只保存一個外鍵,例如:
- 如果產品不為空,則產品屬性需要為空
- 如果 product_attribute 不為 null,則產品必須為 null
注意:
product 和 product_attribute 不能同時為 null。
如何使用 Django 管理員實作這一點。
uj5u.com熱心網友回復:
我會為該模型添加一個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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/346388.html
標籤:姜戈 django-models django-admin 相关内容
