Difference between GET and FILTER in Django model layer
What is the difference, please explain them in laymen's terms with examples. Thanks开发者_JAVA百科!
I don't know if you really need an example, it's quite easy:
- if you know it's one object that matches your query, use get. It will fail if it's more than one.
- otherwise use filter, which gives you a list of objects.
To be more precise:
MyTable.objects.get(id=x).whatever
gives you thewhatever
property of your object.
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.
MyTable.objects.filter(somecolumn=x)
is not only usable as a list, but you can also query it again, something likeMyTable.objects.filter(somecolumn=x).order_by('date')
.- The reason is that it's not actually a list, but a query object. You can iterate through it like through a list:
for obj in MyTable.objects.filter(somecolumn=x)
精彩评论