Django IntegrityError与模型中的关系

时间:2012-09-26 06:04:20

标签: python django

我正在尝试在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

我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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 has more examples for 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)