Add foreign object in memory without saving to database
|Reported by:||cyberkoa@…||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||1.3|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Description (last modified by lukeplant)
class Group: name = models.Chars() def save(): super(self, Group).save() # access foreign objects members = self.groupmember_set.all() class GroupMember: group = models.ForeignKey(Group) member = models.ForeignKey(User)
I have a page to allow people to create Group , and invited existing user to become member.
When form is submitted, Group data and GroupMember data is submitted together.
I would like to override the Group's save function() , and in the save function(), I need to access the GroupMember data.
g = Group(name='abc') gm1 = GroupMember(member=user1, group=g) gm2 = GroupMember(member=user2, group=g) g.groupmember_set.add(gm1) # Add to memory , I do not want to save to db immediately g.groupmember_set.add(gm2) # Add to memory , I do not want to save to db immediately g.save() gm1.save() gm2.save()
Since the .add() function save the related object to db immediately , causing error.
I do not want to save the Group object first , because it will trigger 2 times save()