Wednesday, November 26, 2014

How to make database queries that “filters” results according to tuples of values?

Hi,
let’s assume I have the following model:
 
class Ingredient(models.Model):
    ingredient= models.CharField(max_length=255)
class Dish(models.Model):
    BREAKFAST = 'bf'
    LUNCH = 'l'
    DINNER = 'D'
    DISH_CHOICES = (
        (BREAKFAST, 'Breakfast'),
        (LUNCH, 'Lunch'),
        (DINNER, 'Dinner'),
    )
    dish = models.CharField(max_length=32,choices=DISH_CHOICES,unique=True)
 
class Preference(models.Model):
    ingredient= models.ForeignKey(Ingredient)
    dish = models.ForeignKey(Dish)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True, verbose_name='Date updated')
    owner  = models.ForeignKey(User, related_name='preferences')
 
class Meal(models.Model):
    name = models.CharField(max_length=255)
    ingredient= models.ManyToManyField(Ingredient)
    kalorins = models.IntegerField()
    thumbnail = models.URLField(blank=True)
    dish= models.ForeignKey(Dish)

I want to execute a database query in the view resulting all meals that would match the preference’s of a user.
But something like: result = Meal.objects.filter(ingredient__in=user.request.name.pfreferences) will select all the meals witch are in the preference list of the user, regardless his choice of the “Dish Type”. So if a person only likes tomatos for breakfast, he also will get all meals with tomates for lunch and dinner.
 
So I am looking for a way, which returns only the “Meals” where the ingredients and the dish BOTH match the ingredients and the dish of the user’s Preference.
I haven’t found anything in the django books I have or the documentation
Thanks a lot.
Best Regards,
Mike
 
 

No comments:

Post a Comment