[Django]-Django Queryset and filter() vs get()

97👍

The difference is that filter returns a queryset object, wheras get returns the required object.

If you use filter(), you typically do this whenever you expect more than just one object that matches your criteria. If no item was found matching your criteria, filter() returns am empty queryset without throwing an error.

If you use get(), you expect one (and only one) item that matches your criteria. Get throws an error if the item does not exist or if multiple items exist that match your criteria. You should therefore always use if in a try.. except .. block or with a shortcut function like get_object_or_404 in order to handle the exceptions properly.

Leave a comment