我正在尝试在我的 Offer 表上创建一个约束,该表有一个 offer_id(字符字段)和一个 product_id(外键),其中一个 offer_id 只能与 1 个产品组合。不允许将 offer_id 与多个产品组合。
我不能让 offer_id 简单地唯一,因为该表使用历史数据。如何为我的 django 模型进行约束,以确保每个 offer_id 最多链接到 1 个产品,一个产品可以有多个 offer_id,并且由于历史数据,一个 offer_id 和 product_id 可以多次出现。
报价模型的简单概述:
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}"