Answer the question
In order to leave comments, you need to log in
How to make a manytomany connection correctly?
Good day. There are a couple of models, for example, describing a pizza recipe. Each pizza contains several ingredients. For each of the pizzas, the amount of a certain ingredient may be different, for example, on pizza 1 we add 100 grams of the pepper ingredient, and on pizza 2, only 50 grams of the same pepper ingredient. How to do it in models?
class Ingridient(models.Model):
ingridient_name = models.CharField(u'Название ингридиента', max_length=255)
class Pizza(models.Model):
pizza_name = models.CharField(u'Название пиццы', max_length=255)
ingridients = models.ManyToManyField(Ingridient)
Answer the question
In order to leave comments, you need to log in
Because An M2M field is sugar in jang, it may not be obvious that in the database it is represented by two fields with a unique index on both fields. FK for one model and FK for another model. Additional fields cannot be specified in M2M, so you need to do something like this:
class Ingredient(models.Model):
name = models.CharField(u'Название ингр_е_диента', max_length=255)
class Pizza(models.Model):
name = models.CharField(u'Название пиццы', max_length=255)
ingredients = models.ManyToManyField(Ingredient, through='PizzaIngredient')
class PizzaIngredient(models.Model):
pizza = models.ForeignKey(Pizza)
ingredient = models.ForeignKey(Ingredient)
quantity = models.DecimalField(max_digits=9, decimal_places=2)
unit = models.CharField(max_length=30) # Единица измерения (граммы, ложки). Можно выделить в отдельную таблицу, если надо
class Meta:
unique_together = (('pizza', 'ingredient'),)
djbook.ru/rel1.8/topics/db/models.html#intermediar...
through who did you come up with?
For example, add a Recipe model
class Recipe(models.Model):
ingridient = models.ForeignKey(Ingridient)
quantity = models.DecimalField(...)
class Pizza(models.Model):
pizza_name = models.CharField(u'Название пиццы', max_length=255)
component = models.ManyToManyField(Recipe)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question