查询一个多到许多领域的Django
问题描述:
我有一个多到许多领域的典范是这样的:查询一个多到许多领域的Django
class BillingMonth(models.Model):
month = models.IntegerField(min=1, max=12)
class BillingCycle(models.Model):
description = models.CharField()
months_billed = models.ManyToManyField(BillingMonth)
每个BillingCycle(每月,每季度等)中的一个或多个将得到计费个月。租赁设备型号如下所示:
class RentalEquipment(models.Model):
description = models.CharField()
billing_cycle = models.ForeignKey(BillingCycle)
如何查找应在指定月份进行结算的所有RentalEquipment?这似乎并不工作:
billing_month = BillingMonth(month=8)
RentalEquipment.objects.filter(billing_cycle__months_billed=billing_month)
或者,具有用于BillingCycle模型多对多关系矫枉过正?有没有更好的方法来包含一组日期?
答
它看起来像我可以摆脱查询像这样:
billing_month = BillingMonth(month=8)
billing_cycles = Billing_cycle.objects.filter(months_billed=billing_month)
equipment_needing_billing = RentalEquipment.objects.filter(billing_cycle__in=billing_cycles)
是什么(是)之差(S),你在你的两个方法注意到/个错误? – 2012-08-12 12:07:42