Reputation: 2457
I would like to get queryset of recipes based on groceries queryset. In my models.py I have a grocery model
class Grocery(models.Model):
title = models.CharField(max_length=100)
picture = models.ImageField(upload_to='pictures/groceries', blank=True)
category = models.ForeignKey(Category, unique=False)
I have an recipe model:
class Recipe(models.Model):
title = models.CharField(max_length=100)
chef = models.ForeignKey(settings.AUTH_USER_MODEL, unique=False, related_name='chefs_recipe')
text = models.TextField()
picture = models.ImageField(upload_to='pictures/recipes/title-photos', blank=True)
I have an ingredient model which is basically a many to many junction table
class Ingredient(models.Model):
recipe = models.ForeignKey(Recipe, unique=False, related_name='recipeingredients')
grocery = models.ForeignKey(Grocery, unique=False)
quantity = models.DecimalField(max_digits=10, decimal_places=2)
PRIORITY = (
('high', 'inevitable'),
('average', 'replaceble'),
('low', 'flavoring')
)
priority = models.CharField(max_length=20, choices=PRIORITY)
and I have a queryset of groceries selected by user.
How can I get a queryset of recipes which could be cooked with users groceries? That means I want all recipes which HIGH PRIORITY ingredient.grocery are contained in groceris queryset.
def get_queryset(self):
groceries = Grocery.objets.filter(some_filter)
recipes = ?
All I could think was a loop in which I will check recipe by recipe but it seems mostly inefficient when recipe table will contain lot of data.
any idea?
Upvotes: 0
Views: 62
Reputation: 2569
I think this solve your problem:
def get_queryset(self):
groceries = Grocery.objets.filter(some_filter)
recipes = Recipe.objects.filter(pk__in=Ingredient.objects.filter(priority='high',grocery__in=groceries).values_list('recipe_id', flat=True).distinct())
Upvotes: 1