[Answered ]-Django IntegrityError with relationship in model

1👍

I think you have to give relationship a null=True parameter too.

ingredients = models.ManyToManyField(Ingredients, blank=True, null=True,)

1👍

Your problem is similar to this one: Foreign keys and IntegrityError: id may not be NULL

To fix it, you will do something similar to this when saving:

>>> s = Recipe()
>>> s.name = 'Blah'
>>> obj = Ingredient(...)
>>> obj.save()
>>> s.ingredients = obj
>>> s.save()

The Django Doc has more examples for ManyToManyField. For example, for your case:

>>> i = Ingredient.objects.get(id=1)
>>> e = i.recipe_set.create(
...     name ='strawberry pancake',
... )
# No need to call e.save() at this point -- it's already been saved.

This is equivalent to (but much simpler than):

>>> i = Ingredient.objects.get(id=1)
>>> e = Recipe(
...     ingredients=i,       
...     name='strawberry pancacke',
... )
>>> e.save(force_insert=True)
👤K Z

Leave a comment