I have a “Recipe” model, which contains multiple “Product” models and the relationship between Recipe and Product holds the quantity of the products. Thus, I need a custom intermediary model.
models.py:
class Product(models.Model):
name = models.CharField(max_length=50, null=False, blank=False)
quantity = models.PositiveSmallIntegerField(null=False, blank=False)
...
class Recipe(models.Model):
name = models.CharField(max_length=50, null=False, blank=False)
ingredients = models.ManyToManyField(Product, through='ProductRecipe')
...
class ProductRecipe(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
quantity = models.SmallIntegerField(null=True)
A Recipe object is created based on a form and the Product objects to be part of the Parent object are selected by checkboxes. My question is, how can we add ProductRecipe.quantity field to my form when Recipe object is being created.
Here is my forms.py that I use for Recipe object creation
class RecipeForm(ModelForm):
class Meta:
model = Recipe
fields = ['name ', ... , 'ingredients']
ingredients = forms.ModelMultipleChoiceField(
queryset=Product.objects.all(),
widget=forms.CheckboxSelectMultiple
)
Trying to have additional field ‘quantity’ while creating Recipe object from django form
Paddy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.