Tuesday, October 6, 2009

Re: Getting model's ID in save() method

On Tue, Oct 6, 2009 at 12:05 PM, Aaron <aaron@genieknows.com> wrote:

When saving a model, I need to be able to access its ID field like
this:

class MyModel:
   ...
   def save(self, force_insert = False, force_update = False):
       v = self.id
       # Do something with v

       super(MyModel, self).save(force_insert, force_update)

However, if the model is being created for the first time, self.id is
None, so I need a way to find out what the ID is going to be.

So far I've come up with this:

class MyModel:
   ...
   def save(self, force_insert = False, force_update = False):
       v = self.id

       if not v:
           if MyModel.objects.count() > 0: # Do other MyModel objects
already exist?
               v = MyModel.objects.latest(field_name = 'id').id + 1
           else:
               v = 1

       # Do something with v

       super(MyModel, self).save(force_insert, force_update)

Am I calculating the correct ID here?

No.  First there is a race condition here, and you might get multiple threads of control deciding on the same number for v.  Second you are not guaranteed that the DB will assign the next highest number.  One way I know of to make it fail, on some DBs, is to rollback insertions.  The automatically-assigned primary key values used for the rolled back insertions won't necessarily be re-used for subsequent insertions.

The only sure way to know what primary key is going to be assigned by the DB is to actually save the object to the DB and see what got assigned.

Karen

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate