Модель:
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(receivecomponent__in = list_of_available_components).distinct()
получить рецепты (из list_of_related_receipts), в которых нет хотя бы одного компонента
list_of_incomplete_recipes = (ВЫБЕРИТЕ * ИЗ drinkbook_receiptcomponent ЛЕВЫЙ ПРИСОЕДИНЯЙТЕСЬ к drinkstore_stock_products, ИСПОЛЬЗУЯ (product_id), ГДЕ drinkstore_stock_products.stock_id ЯВЛЯЕТСЯ НУЛЕВЫМ, И Receipt_id В (ВЫБЕРИТЕ Receipt_id ИЗ drinkbook_receiptcomponent ПРИСОЕДИНЯЙТЕся к drinkstore_stock_products, ИСПОЛЬЗУЯ (product_id)))
получить рецепты (из list_of_related_receipts), которых нет в «list_of_incomplete_recipes»