简体   繁体   English

Django-禁用相关集中的重复项

[英]Django - disable duplicates in related set

There is a class Order , SubOrder and class Product . 有一个类OrderSubOrder和类Product I want to make sure that no Order object will contain multiple SubOrder objects with the same Product object. 我想确保没有Order对象将包含具有相同Product对象的多个SubOrder对象。

class Order(TimeStampedModel):
    ....

class SubOrder(models.Model):
    order = models.ForeignKey('orders.Order', on_delete=models.CASCADE, related_name='suborders')
    product = models.ForeignKey('products.Product', on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(verbose_name='Počet')

So if there were 3 products - A, B, C 因此,如果有3种产品-A,B,C

I don't want allow one Order object to have multiple SubOrders with the same Product . 我不想让一个Order对象具有同一Product多个SubOrders For example Order[Suborder[A,12],Suborder[B,12],Suborder[B,5]] should raise ValidationError because there are two SubOrders with the same Product B . 例如Order[Suborder[A,12],Suborder[B,12],Suborder[B,5]]应该引发ValidationError因为有两个具有相同Product B的子 SubOrders

Is it possible to do that on the model or database layer? 是否可以在modeldatabase层上执行此操作?

EDIT 编辑

I tried this: 我尝试了这个:

def clean(self):
    neighbour_suborders = self.order.suborders.filter(product=self.product)
    if self.pk:
        neighbour_suborders = neighbour_suborders.exclude(pk=self.pk)
    if neighbour_suborders.exists():
        raise ValidationError("Takýto produkt už v objednávke existuje!")

But it allows to create such order in Django admin. 但是它允许在Django admin中创建这样的顺序。

A unique constraint for order and product prevents saving more than one suborder for the same order and the same product: 订单和产品的唯一约束可防止为同一订单和同一产品保存多个子订单:

class SubOrder(models.Model):
    class Meta:
        unique_together = ('order', 'product',)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM