I often see that, regardless of the model, people often use Model.objects.get(id=id) or .get(product_name=product_name) or .get(cart=my_cart) -- but I now see a piece of code that is using .get() like it's a filter such as .get(product=product, cart=my_cart), is this going to work as intended?
Asked
Active
Viewed 30 times
0
-
1Does this answer your question? [Difference between Django's filter() and get() methods](https://stackoverflow.com/questions/3221938/difference-between-djangos-filter-and-get-methods) – Abdul Aziz Barkat May 20 '22 at 04:38
1 Answers
1
.get() is used to only return one record, as opposed to .filter() which returns a set of records. You can use as many criteria as you like in order to positively identify that one record.
An example might be:
the_batman = Movie.objects.get(category = "superhero", lead__full_name="Robert Pattinson")
In this case, either criteria alone will produce a set of many movies (and thus error out in a .get() request), but in combination they will only produce one, and so is working as intended.

SamSparx
- 4,629
- 1
- 4
- 16