Opened 13 years ago

Closed 13 years ago

Last modified 13 years ago

#17253 closed New feature (wontfix)

Add foreign object in memory without saving to database — at Version 1

Reported by: cyberkoa@… Owned by: nobody
Component: Database layer (models, ORM) Version: 1.3
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Luke Plant)

Similar to the following post
http://stackoverflow.com/questions/7908349/django-making-relationships-in-memory-without-saving-to-db?answertab=active#tab-top

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.

Example code

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()

Change History (1)

comment:1 by Luke Plant, 13 years ago

Description: modified (diff)
Resolution: wontfix
Status: newclosed

Formatting fixed, please use 'Preview' to check formatting, thanks.

If we don't save M2M objects to the DB immediately when running add(), when do we save them? save() doesn't do that, we would need a 'flush-everything-to-the-database' call, which we don't have. Adding one would require a fundamental change to the way that the ORM works - essentially something like the unit-of-work pattern in SQLAlchemy.

I'm therefore closing WONTFIX.

Note that saving the Group object first doesn't necessarily mean you need to call save() twice - the add() calls do not need to be followed by save(). (I'm guessing you may have reasons why it is this way in your case, but I don't think the situation is forced on you by Django).

Note: See TracTickets for help on using tickets.
Back to Top