Frank
Frank

Reputation: 2837

How to query many to many relationships on django?

I'm writing an app for food recipes. I want it to be able to discriminate recipes avoiding specific food intolerances (i.e. lactose, eggs, gluten, SO2...). I've come up with this model for that:

models.py

from django.db import models
from unittest.util import _MAX_LENGTH

class Alimento(models.Model):
    INTOLERANCIAS = (
        ('00', 'Ninguna'),
        ('GL', 'Gluten'),
        ('CR', 'Crustáceos'),
        ('HU', 'Huevos'),
        ('FS', 'Frutos Secos'),
        ('AP', 'Apio'),
        ('MO', 'Mostaza'),
        ('SE', 'Sésamo'),
        ('PE', 'Pescado'),
        ('CA', 'Cacahuetes'),
        ('SO', 'Sulfitos'),
        ('SJ', 'Soja'),
        ('LA', 'Lácteos'),
        ('AL', 'Altramuz'),
        ('ML', 'Moluscos'),
        ('CA', 'Cacao'),


    )
    nombre = models.CharField(max_length=60)
    intolerancia = models.CharField(max_length=2, choices=INTOLERANCIAS)

    def __str__(self):
        return self.nombre


class Receta(models.Model):
    nombre = models.CharField(max_length=100)
    raciones = models.IntegerField(default=1)
    preparacion = models.TextField(default='')
    consejos = models.TextField(blank=True)
    ingredientes = models.ManyToManyField(Alimento, through='Ingrediente')

    def __str__(self):
        return self.nombre


class Ingrediente(models.Model):
    receta = models.ForeignKey('recetas.Receta', on_delete=models.CASCADE)
    alimento = models.ForeignKey('recetas.Alimento', related_name='ingredientes', on_delete=models.CASCADE)
    cantidad = models.FloatField(default=0)
    descripcion = models.CharField(max_length=60, blank=True)

    def __str__(self):
        return self.alimento.__str__()

I've registered them in admin.py and I can create/update/delete them ok, but I don't see the manytomany field anywhere inb the admin UI.

admin.py from django.contrib import admin

from .models import Alimento, Receta, Ingrediente

admin.site.register(Alimento)
admin.site.register(Receta)
admin.site.register(Ingrediente)

So I went to shell and tried some queries there

Alimento.objects.all()
<QuerySet [<Alimento: Pan>, <Alimento: Tomate>, <Alimento: Vinagre de vino>, <Alimento: Ajo>, <Alimento: Pimiento Verde>, <Alimento: Sal>, <Alimento: Aceite de Oliva>]>


Receta.objects.all()
<QuerySet [<Receta: Gazpacho>]>


gaz = Receta.objects.get(nombre='Gazpacho')
Ingrediente.objects.filter(receta=gaz)
<QuerySet [<Ingrediente: Pan>, <Ingrediente: Tomate>, <Ingrediente: Tomate>, <Ingrediente: Pimiento Verde>, <Ingrediente: Aceite de Oliva>, <Ingrediente: Vinagre de vino>, <Ingrediente: Ajo>]>

pan = Alimento.objects.get(nombre='Pan')
pan.intolerancia
'GL'

Given this, how can I query recipies (Receta) for a given intolerance/allergy (Alimento:intolerancia) ?

Upvotes: 0

Views: 77

Answers (2)

Wilfried
Wilfried

Reputation: 1633

You can acces to Alimento model, with the field ingredientes of your model Receta. In your filter you can use it, and check the field intolerancia of Alimento

Receta.objects.filter(ingredientes__intolerancia='GL')

Update after question in comment, see documention

Receta.objects.filter(ingredientes__intolerancia_in=['GL', 'CR'])

Upvotes: 1

itzMEonTV
itzMEonTV

Reputation: 20339

Direct solution

class IngredienteInline(admin.TabularInline):
    model = Ingrediente
    extra = 1

class AlimentoAdmin(admin.ModelAdmin):
    inlines = (IngredienteInline,)

class RecetaAdmin(admin.ModelAdmin):
    inlines = (IngredienteInline,)

Then,

admin.site.register(Alimento, AlimentoAdmin)
admin.site.register(Receta, RecetaAdmin)

Reference doc

Now the query for filter is

Receta.objects.filter(ingredientes__intolerancia ='CR')

Upvotes: 1

Related Questions