5

(下面的所有代码都是实际代码的简化表示)。

如果我有以下 Django 模型:-

class Material(models.Model):
    name = models.CharField(max_length=110)

class OrderDetail(models.Model):
    material = models.ForeignKey(Material)
    order_quantity = models.IntegerField()
    quantity_delivered = models.IntegerField(null=True, blank=True)
    is_open = models.BooleanField()
    is_active = models.BooleanField()

class MaterialRequirement(models.Model):
    material = models.ForeignKey(Material)
    quantity = models.IntegerField()

我有一个MaterialRequirement模型实例,我们称之为material_requirement。我正在尝试检索OrderDetail满足以下条件的对象:-

1. material = material_requirement.material

2. is_open = True

3. is_active = True

4. order_quantity > quantity_delivered

5. material_requirement.quantity <= order_quantity - quantity_delivered

我的问题是如何在下面的 ORM 查询中合并第 5 个选择标准。

order_details = OrderDetail.objects.select_related('material').filter(material=material_requirement.material,
                                                                    is_open=True,
                                                                    is_active=True,
                                                                    order_quantity__gt=F('quantity_delivered'))
4

2 回答 2

2
order_details = (OrderDetail.objects.select_related('material')
                 .filter(material=material_requirement.material,
                         is_open=True,
                         is_active=True,
                         order_quantity__gt=F('quantity_delivered'),
                         quantity_delivered__gte=F('order_quantity') - material_requirement.quantity,
                         )
)
于 2013-03-23T12:13:27.450 回答
0
order_details = order_detail.extra(where=["order_quantity - quantity_delivered <= %d" % material_requirement.quantity]))
于 2013-03-23T11:46:02.603 回答