Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

python - Difference between GET and FILTER in Django model layer

What is the difference, please explain them in laymen's terms with examples. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...