Home > Software design >  Django Admin one field required related on other field
Django Admin one field required related on other field

Time:11-03

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 :

  • If the product is not null then the product attribute needs to be null
  • Same thing for the product_attribute if its not null then the product must be null
    Note:
    product and product_attribute cannot be null at the same time .

    how to achieve this using the Django admin.

CodePudding user response:

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