Saving related model objects

I have two related models (one for many) in my django application 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 message that says "the value is null in the column and violates the foreign key, not the null constraint."

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

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

+3
source share
1 answer

, Foreign Key, . objBlog.entry_set.add(objEntry1) django save() .

add:

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

Source: https://habr.com/ru/post/1744689/


All Articles