簡體   English   中英

Django Admin 需要與其他字段相關的一個字段

[英]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)
   

目標是只保存一個外鍵,例如:

  • 如果產品不為空,則產品屬性需要為空
  • product_attribute 同樣的事情,如果它不為空,那么產品必須為空
    筆記:
    product 和 product_attribute 不能同時為空。

    如何使用 Django 管理員實現這一點。

我會向該模型添加一個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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM