Friday, January 17, 2014

Re: Fast and Easy way to check if an instance of an Model exists in the Database

Den 16/01/2014 kl. 17.50 skrev Johannes Schneider <johannes.schneider@galileo-press.de>:

> The point is, I have to distinguish between an instance which is created, but its save method is not yet called. And an instance coming from the database via a manager.

Okay, then create an instance variable on the model instances when you create them manually. Something like this:

obj = InstanceModel()
obj.pk = 123
obj.manually_created = True

Then have your save() method check for this variable:

def save(self, *args, **kwargs):
if getattr(self, 'manually_created', False):
# Was created manually. Do something
else:
# From database. Do something else
super(self, InstanceModel).save(*args, **kwargs)
del obj.manually_created


Erik

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/BA80A159-B4D0-4559-98E5-779EFE6717A7%40cederstrand.dk.
For more options, visit https://groups.google.com/groups/opt_out.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate