S
S
Stanislav2017-04-26 16:41:43
Django
Stanislav, 2017-04-26 16:41:43

In Django 1.11, how do I create additional fields for a many-to-many relationship?

from django.db import models
from food.models import Food

class Recipe(models.Model):
    description = models.TextField(null=True, blank=True)
    ingridients = models.ManyToManyField(
        Food,
        through=Ingredients,
        through_fields=('recipe', 'food')
    )

class Ingredients(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    food = models.ForeignKey(Food, on_delete=models.CASCADE)
    quantity = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2)

I did according to the documentation , but I get an error in Recipe through=Ingredients, NameError : name 'Ingredients' is not defined

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
neatsoft, 2017-04-26
@Chebaa

because the Ingredients class has not yet been declared at the time of use, its name must be enclosed in quotation marks:

...
    ingridients = models.ManyToManyField(
        Food,
        through='Ingredients',
        through_fields=('recipe', 'food')
    )
...

lazy relationships

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question