简体   繁体   English

Django ManyToMany通过模型实现

[英]Django ManyToMany with through model implementation

So let's say I have these models in my Django app: 因此,假设我的Django应用程序中包含以下模型:

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). 现在,我要访问食谱的成分(确实是RecipeIngredients)。 Via the Django shell: 通过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. 理想情况下,我希望能够拥有一个Recipe对象并直接从中获取RecipeIngredients。

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 : 使用related_name ,就像使用普通的ForeignKeyManyToManyField

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Through模型的ManyToMany的Django交集 - Django intersection of ManyToMany using Through model 通过中间模型具有许多内容的Django表单集 - Django formset with manytomany through intermediate model Django 通用视图 ManyToMany 与“通过”模型 - Django Generic Views ManyToMany with "through" model Django内联formset通过另一个模型过滤多种关系 - Django inline formset filters in manytomany relationship through another model Django模型:亲戚模型是否应该通过ForeignKey或ManyToMany引用自身? - Django Models: Should a relatives model refer to itself through ForeignKey or ManyToMany? Django:通过相关的 OneToOne model 使用 through 参数序列化 ManyToMany 关系 - Django: Serialize a ManyToMany relationship with a through argument via a related OneToOne model Django CreateView动态字段表单,用于ManyToMany至 - Django CreateView dynamic fields form for model with ManyToMany through Django-rest-framework通过模型放置许多 - django-rest-framework PUT manytomany through model django_filters 通过 model 在 ManyToMany 中的字段上搜索 - django_filters search on field in ManyToMany through model Django ManyToMany通过关系 - Django ManyToMany Through Relationship
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM