【问题标题】:Django Admin one field required related on other fieldDjango Admin 一个字段需要与其他字段相关
【发布时间】:2021-11-02 09:14:26
【问题描述】:

我正在使用 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 不能同时为空。

    如何使用 Django 管理员来实现这一点。

【问题讨论】:

    标签: django django-models django-admin related-content


    【解决方案1】:

    我会为该模型添加一个clean() method。 这样的方法可以实现为:

    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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2018-12-28
      • 1970-01-01
      • 2022-12-14
      相关资源
      最近更新 更多