如何在django 1.9中保存多对一对象

时间:2016-02-23 05:31:03

标签: django django-models

我是django的新手,我遇到了这个错误

IntegrityError: NOT NULL constraint failed: boxes_suggestion.box_id

这是我的模特

class Box(models.Model):
    """
    Box model
    """
    def __str__(self):
        return self.title
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)     
    title = models.CharField(max_length=40, blank=True, null=True)
    slug = AutoSlugField(_('slug'), populate_from="id")
    identify = models.BooleanField(default=False)

class Suggestion(models.Model):
    """
    Suggestion model
    """
    def __str__(self):
        return self.content[0:10]

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)     
    box = models.ForeignKey(Box, on_delete=models.CASCADE)
    content = models.CharField(max_length=250, blank=True, null=True)

A Box(建议框)有很多建议,但是当我尝试创建一个建议s = Suggestion(content=fake.text()).save() 时,我收到上面提到的错误

1 个答案:

答案 0 :(得分:1)

Suggestion.boxBox的外键,不能为null。保存Suggestion对象时,必须将其分配给现有的Box。

test_box = Box.objects.create(title='test box')

# now we can save suggestion
s = Suggestion(box=test_box, content=fake.text())
s.save()