Vinh Nguyen
Vinh Nguyen

Reputation: 49

Django ORM objects.get() Related Questin: Is it legit to use .get() as if it's .filter()?

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?

Upvotes: 0

Views: 37

Answers (1)

SamSparx
SamSparx

Reputation: 5257

.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.

Upvotes: 1

Related Questions