[Fixed]-How can I make sure that every child is meeting one condition on Django Models?

1πŸ‘

βœ…

I don’t know how your model looks like, but here is a possible approach

# Possible models.py
class Recipe(models.Model):
    ingredients = models.ManyToManyField('Ingredient', related_name='in_recipes')
    ...

class Ingredient(models.Model):
    name = models.CharField(...)

# views.py
from django.db.models import Q

# Use Q objects to create a query that requires all ingredients
ingredient_query = None
for an_ingredient in REQUIRED_INGREDIENTS:
    ingredient_query = ingredient_query & Q(ingredients=an_ingredient) if ingredient_query else Q(ingredients=an_ingredient)

recipes_with_ingredients = Recipe.objects.filter(ingredient_query)
πŸ‘€Tiny Instance

Leave a comment