views:

54

answers:

2

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?

+4  A: 

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.

celopes
Also note that `get` throws a `DoesNotExist` exception when the object is not found and throws a `MultipleObjectsFound` exception when there are more than one. `filter` on the other hand returns an empty list in the former case and obviously handles the latter case.
Joe Holloway
+4  A: 

.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%5For%5Fcreate/ 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

brianray