1

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}"
Mathijs
  • 177
  • 3
  • 18
  • Does the historical data allow multiple product per offer? Because it should be possible to support this by making `offer_id` unique, and adding a unique constraint on both `offer_id` and `product`. – Brian Destura Aug 29 '21 at 13:20
  • It is possible to have for example: `offer_id | product_id | time` `1 | 1 | today` `2 | 1 | today` `1 | 1 | yesterday` `2 | 1 | yesterday` `3 | 2 | today` `3 | 2 | yesterday` 1 offer only has 1 product. However, A single unique product can have multiple offers. However, the same product can be listed multiple times due to the historical data. – Mathijs Aug 29 '21 at 13:31

0 Answers0