Sunday, May 26, 2013

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

What are you trying to accomplish?

I believe the doc's talk about this some; but in short,  you can only check the pk if its a new object; otherwise the pk would be set (if you retrieved the object from the database, or saved before).

I would assume (as i've not run into the issue yet) that on a save() to the object, if it fails you'll get an exceptions thrown.

On Saturday, May 25, 2013 4:01:29 PM UTC-4, Sergiy wrote:
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