Saturday, May 25, 2013

Is there a way to tell an instance was saved without checking instalce.pk or doing a db lookup?

To check if the instance was saved one might do something like this:

def is_instance_saved(instance):
    if instance.pk is None:
        return False
    # in case pk was set manually
    try:
        instance.__class__.objects.get(pk=instance.pk)
    except ObjectDoesNotExist:
        return False
    return True

I wonder if the instance already knows whether it was saved or not (through some sort of private attribute).

Thanks
Sergiy

--
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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment