简体   繁体   中英

Django ManyToMany with through model implementation

So let's say I have these models in my Django app:

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

    def __unicode__(self):
        return self.name

class Recipe(models.Model):
    name = models.CharField(max_length=100)
    ingredients = models.ManyToManyField(Ingredient, 
        through='RecipeIngredient')

    def __unicode__(self):
        return self.name

class RecipeIngredient(models.Model):
    recipe = models.ForeignKey(Recipe)
    ingredient = models.ForeignKey(Ingredient)
    quantity = models.DecimalField(max_digits=4, decimal_places=2)
    unit = models.CharField(max_length=25, null=True, blank=True)

    def __unicode__(self):
        return self.ingredient.name

Now I want to access a recipe's ingredients (really RecipeIngredients). Via the Django shell:

>>> r = Recipe.objects.get(id=1)
>>> ingredients = RecipeIngredients.objects.filter(recipe=r)

This seems counter-intuitive and clunky to me. Ideally I'd like to be able to have a Recipe object and get RecipeIngredients from it directly.

Is there a more elegant implementation of my models? Is there any way to improve my existing model implementation?

Use related_name , just as you would with a normal ForeignKey or ManyToManyField :

class RecipeIngredients(models.Model):
    recipe = models.ForeignKey(Recipe, related_name='ingredient_quantities')

And then:

>>> r = Recipe.objects.get(id=1)
>>> ingredients = r.ingredient_quantities.all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM