Django Recipe Website Model Structure

I am working on a Django site, which should give the opportunity to choose recipes containing ingredients provided by the user. So, in short, the idea of ​​the site is "the things you can do from food in your refrigerator."

So, I made 2 models

class Recipe (models.Model): name = models.CharField(max_length=255) ingredients = models.ManyToManyField(Ingredient) class Ingredient (models.Model): name = models.CharField(max_length=255) 

Imagine that I have a list ['egg','bread','meat','onion'] .

Now I need to select all the recipes that can be made from this list of ingredients. The problem is that some recipes may contain only some of the ingredients on the list.
For instance:

  • Egg Toast = Egg + Bread
  • Meat egg Toast = meat + egg + bread
  • Meat with onions = meat + onions
  • etc.

So my question is: is it possible to select all the recipes that could be made from a list of ingredients. And choose the closest recipes that could be made from the list of ingredients + some ingredients from the store?

For example: recipes has 3 elements out of 4, so we add them to the result.

+4
source share
2 answers

I think I found one solution. Using code

 from itertools import chain, combinations def all_subsets(ss): return chain(*map(lambda x: combinations(ss, x), range(0, len(ss)+1))) 

I can select all possible combinations of ingredients from the lists.

 for s in all_subsets(['egg','bread','meat','onion']): if len(s)>2: print s 

Gives me the result

("egg", "bread", "meat") ("egg", "bread", "onion") ("egg", "meat", "onion") ("bread", "meat", "onion ") (" egg "," bread "," meat "," onion ")

Now the problem is how to optimize the query so that I can select all recipes containing a list of this ingredient. In MongoDB, I used

 receipts.find({'ingredients.name':{'$all':ingredients_list}}) 

Is there an alternative solution for MySQL?

0
source

You tried:

 Receipt.objects.filter(ingredients__name__in=['egg','bread','meat','onion']) 
+3
source

Source: https://habr.com/ru/post/1394213/


All Articles