tags:

views:

49

answers:

1

What is the difference between

mymodel=model.objects.get(name='pol')

and

mymodel=model.objects.filter(name='pol')
+6  A: 

The Django QuerySet docs are very clear on this:

get(**kwargs)¶

Returns the object matching the given lookup parameters, which should be in the format described in Field lookups.

get() raises MultipleObjectsReturned if more than one object was found. The MultipleObjectsReturned exception is an attribute of the model class.

get() raises a DoesNotExist exception if an object wasn't found for the given parameters. This exception is also an attribute of the model class.

filter(**kwargs)

Returns a new QuerySet containing objects that match the given lookup parameters.

Basically use get when you want to get a single unique object, and filter when you want to get all objects that match your lookup parameters.

sdolan
Ok! Thanks. Very usefull!
Pol
From the FAQ (http://stackoverflow.com/faq): When you have decided which answer is the most helpful to you, mark it as the accepted answer by clicking on the check box outline to the left of the answer. This lets other people know that you have received a good answer to your question. Doing this is helpful because it shows other people that you're getting value from the community. Just wanted to point that out because you haven't accepted any of your questions. I would suggest going back to your other questions and accepting the answer you found most usefull.
sdolan
I didn't know this. Thanks!
Pol
No problem and thank you. I could tell you probably didn't based on the 0% acceptance rate. See you also got a real username and went through and accepted a good portion those old questions. I'm sure the other users will appreciate it as well.
sdolan