Let's start with the models:
class Brand(models.Model):
id = models.UUIDField(primary_key=True
name = models.CharField(max_length=255)
class ProductLine(models.Model):
id = models.UUIDField(primary_key=True
name = models.CharField(max_length=255)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
class Product(models.Model):
id = models.UUIDField(primary_key=True
name = models.CharField(max_length=255)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
product_line = models.ForeignKey(ProductLine, on_delete=models.CASCADE, blank=True, null=True)
So we have brands. Brands can have 0 or more product_lines. A product always has a brand, and may also be within a product_line.
My goal is to constrain the product_line of a product to also have the same brand as the product itself.
For example:
- Brand A has 2 product_lines: Premium, Standard
- Brand B has 1 product_line: Platinum
Suppose we have a product that belongs to brand B. I want to allow the product_line to be either null or Platinum, but not one of the product_lines that belong to Brand A (Premium or Standard)
I'm not sure how to achieve this, or even if this should happen in serializers, at the model level, or somewhere else. Any help from seasoned django-ers would be much appreciated!