Reputation: 305
I'm working on Django website that should give a possibility to select cooking recipes containing the ingredients provided by user. So in brief, the idea of the site is "things you could make from the 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)
Let's imagine, that I have as list ['egg','bread','meat','onion']
.
Now I need select all Recipes that could be made from that list on ingredients.
The problem is, that some recipes may have only some of ingredients from the list.
For example:
So my question is: could it be possible to select all recipes that could be made from the list of the ingredients AND select the closest recipes that could be made from the list of ingredients + some ingredients from the shop?
For example: recipes has 3 elements from 4, so we add it to the result.
Upvotes: 5
Views: 2474
Reputation: 305
I think I found one solution. Using the code
from itertools import chain, combinations
def all_subsets(ss):
return chain(*map(lambda x: combinations(ss, x), range(0, len(ss)+1)))
I'm able to 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 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 I can select all recipes containing the list of this ingredient. In MongoDB I was using
receipts.find({'ingredients.name':{'$all':ingredients_list}})
Is there any alternative solution for MySQL?
Upvotes: 0
Reputation: 7631
Have you tried:
Receipt.objects.filter(ingredients__name__in=['egg','bread','meat','onion'])
Upvotes: 3