I am trying to create a constraint on my Offer table, which has an offer_id (charfield) and a product_id (foreign key) where an offer_id can only be combined with 1 product. It is not allowed that an offer_id is combined with multiple products.

I can not make offer_id simply unique, since this table uses historical data. How can I make a constraint for my django Model, which makes sure that every offer_id is at most linked to 1 product, a product can have multiple offer_ids and a single offer_id and product_id can occur multiple times due to historical data.

Simple overview of offer model:

class Offer(models.Model):
    offer_id = models.CharField(max_length=45, default=-1)
    seller = models.ForeignKey(Seller, on_delete=models.CASCADE, null=True, blank=True)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    time = models.DateTimeField(default=timezone.now)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['offer_id'], condition=?, name='unique_offer_product')
        ]
        

    def __str__(self):
        return f"Product {self.product} with seller {self.seller} has offer_id {self.offer_id}"
0

There are 0 answers