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)
   

目标是只保存一个外键,例如:

我会为该模型添加一个 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")