Reputation: 7508
Is there a difference in the result between:
MyModel.objects.filter(pk=1)
and
MyModel.objects.get(pk=1)
If there is no difference, then why does the .get() method exist?
Upvotes: 1
Views: 1183
Reputation: 1169
.get() always returns that object if it exists (and if there is exactly one). It also raises an exception if it does not exist. For example
blah = MyModel.objects.get(pk=1)
blah is an instance of MyModel. .filter() on the other hand does not return an error if it does not exist.
blah = MyModel.objects.filter(pk=1234234234)
Then blah is a an empty query. You can check this by calling .count() on blah. if blah.count() == 0 means that there is no MyModel items with the key 1234234234. Likewise, if there are many items with that query say:
blah = MyModel.objects.filter(name__contains="Brian")
The you get a query result that can be interated over to get each result:
for b in blah:
print b.name
Also, another interesting method simular to .get() is .get_or_create() http://www.djangoproject.com/documentation/models/get_or_create/ With this you can say:
blah,created = MyModel.objects.get_or_create(name="Brian Ray",
cool=False,
fun=True)
If there already is a BrianRay that would normally been returned with the .get() it just returns that instance; otherwise, it creates it. Notice it returns two things. The second is just a flag to let the caller know what actually happened.
HTH, Brian Ray
Upvotes: 7
Reputation: 6394
Filter returns a list of MyModels (in this case a list of one). Get returns one instance of MyModel.
By the way: you can test these things by running:
manage.py shell
from myapp import models
models.MyModel.objects.filter(pk=1)
models.MyModel.objects.get(pk=1)
Look at the output of that.
Upvotes: 4