Monday, October 23, 2017

Re: DoesNotExist behavior in db.models query.py



On Oct 23, 2017 4:06 PM, "'Aaron C. de Bruyn' via Django users" <django-users@googlegroups.com> wrote:
The difference between .filter() and .get() is definitely 'by-design'.

When you filter through a list of objects, you could end up with zero,
one, or many objects returned.

When you call .get(), you are basically saying "I want to get exactly
*one* record".  If the record is not found, it is considered an error.

One additional difference is that .filter() returns a list of zero or
more objects whereas .get() returns the object you requested or it
throws an error.

A further distinction is that .filter() returns a single Queryset object, not a list of objects found via the query. It is only converted to a true list of objects when it is used (lazy), meaning that the query to the DB is delayed until the last possible moment. This allows for chaining of multiple .filter() calls or other ORM operations to be appended before the DB query is executed.

A .get() call returns the actual object, meaning that you can't chain other filters on to it.

A small distinction, but can land you in trouble if the database state changes between the creation of a Queryset object and when it is actually executed.

-James

--
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciUbxU3W7HZuD3gWyx-W%2BhvV_Udqx1Mmdb0714BM2ChvPg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment