模特:
class Product(models.Model):
name = models.CharField(max_length = 128)
def __unicode__(self):
return self.name
class Receipt(models.Model):
name = models.CharField(max_length=128)
components = models.ManyToManyField(Product, through='ReceiptComponent')
class Admin:
pass
def __unicode__(self):
return self.name
class ReceiptComponent(models.Model):
product = models.ForeignKey(Product)
receipt = models.ForeignKey(Receipt)
quantity = models.FloatField(max_length=9)
unit = models.ForeignKey(Unit)
def __unicode__(self):
return unicode(self.quantity!=0 and self.quantity or '') + ' ' + unicode(self.unit) + ' ' + self.product.genitive
这个想法: 库存中有一个组件。我想知道我可以使用我所拥有的组件制作哪些配方。
这并不容易 - 但可能 - 我创建了一个SQL视图,它可以获得解决方案。但是我正在学习python和Django,所以我想把它变成Django风格; D
解决方案的概念:
获取最后一个组件的配方集:
list_of_available_components = ReceiptComponent.objects.filter(product__in = list_of_available_products).distinct() list_of_related_receipts = Receipt.objects.filter(receiptcomponent__in = list_of_available_components).distinct()
获取最后一个组件的配方(来自list_of_related_receipts)
list_of_incomplete_recipes =(SELECT * FROM drinkbook_receiptcomponent LEFT JOIN drinkstore_stock_products USING(product_id)WHERE drinkstore_stock_products.stock_id IS NULL AND receipt_id IN(SELECT receipt_id FROM drinkbook_receiptcomponent JOIN drinkstore_stock_products USING(product_id)))
获取不在“list_of_incomplete_recipes”中的食谱(来自list_of_related_receipts)
答案 0 :(得分:0)
嘿。我是多么愚蠢。这可以更容易解决。我不必找到至少有一个组件的配件。我可以(以同样的方式!)找到我不能做的食谱,因为至少有一个我没有的成分。
list_of_unavailable_components = ReceiptComponent.objects.exclude(product__in=list_of_available_products).distinct()
现在。
list_of_available_receipts = Receipt.objects.exclude(receiptcomponent__in = list_of_unavailable_components).distinct()
简单干净。谢谢合作; D