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

> Hi List,
> I need to check, if a given instance of a Model already exists in the 
> Database. I cannot check 'instance.pk is None', because there are manually 
> given PKs (no discussion about this plz).
> 
> Up to now I check if 'instance._state.adding' is true. But I don't like this 
> solution.
> Checking 'InstanceModel.objects.exists(pk=self.pk)' generates too much 
> queries, so this is not acceptable in my case.

Can you elaborate on “too much queries”? exists() is supposed to be the 
cheapest way of checking if the object exists. It seems like you want to check 
the database, without actually checking the database…

If you want to check a large number of objects at the same time, just do 
something like:

   InstanceModel.objects.filter(id__in=(your, list, of, PKs)).values_list('id', 
flat=True)

to get all pre-existing PKs in one query.

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+unsubscr...@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/4848B682-ECB2-4DC9-83A7-5C7D58DE0EFF%40cederstrand.dk.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to