开发者

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 the whatever 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 like MyTable.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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜