开发者

Saving related model objects

I h开发者_开发问答ave two related models (one to many) in my django app and When I do something like this

ObjBlog = Blog()
objBlog.name = 'test blog'

objEntry1 = Entry()
objEntry1.title = 'Entry one'

objEntry2 = Entry()
objEntry2.title = 'Entry Two'

objBlog.entry_set.add(objEntry1)
objBlog.entry_set.add(objEntry2)

I get an error which says "null value in column and it violates the foreign key not null constraint".

None of my model objects have been saved. Do I have to save the "objBlog" before I could set the entries? I was hoping I could call the save method on objBlog to save it all.

NOTE: I am not creating a blog engine and this is just an example.


I would guess that one of your models has a Foreign Key field which is not nullable. When you do objBlog.entry_set.add(objEntry1) django calls save() on each object.

This is how the add method looks like:

def add(self, *objs):
    for obj in objs:
        if not isinstance(obj, self.model):
            raise TypeError("'%s' instance expected" % self.model._meta.object_name)
        setattr(obj, rel_field.name, instance)
        obj.save()
add.alters_data = True
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜