1

我正在尝试在 Django 中创建配方/配料模型

在我的models.py中,我得到了

class Ingredient(models.Model):
    name = models.CharField(max_length=20)

class Recipe(models.Model):
    name = models.CharField(max_length=50)
    ingredients = models.ManyToManyField(Ingredient, blank=True)

但是当我在我的管理员中创建食谱或成分时,我得到:

IntegrityError at /admin/menuview/ingredient/add/
menuview_ingredient.recipe_id may not be NULL

我在这里做错了什么?

4

2 回答 2

1

您的问题与此类似:Foreign keys and IntegrityError: id may not be NULL

要修复它,您将在保存时执行类似的操作:

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

Django Doc 有更多的ManyToManyField例子。例如,对于您的情况:

>>> 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.

这相当于(但比简单得多):

>>> i = Ingredient.objects.get(id=1)
>>> e = Recipe(
...     ingredients=i,       
...     name='strawberry pancacke',
... )
>>> e.save(force_insert=True)
于 2012-09-26T06:19:17.510 回答
1

我认为你也必须给关系一个 null=True 参数。

ingredients = models.ManyToManyField(Ingredients, blank=True, null=True,)
于 2012-09-26T06:12:48.747 回答