djangodjango-modelsdjango-adminrelated-content

Django Admin one field required related on other field


I am using Django admin to save models my model is like bellow:

    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)
   

The goal is to save only one of the foreign keys for example :


Solution

  • I would add a clean() method to that model. Such a method can be implemented as:

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