Django Queryset和filter()vs get() [英] Django Queryset and filter() vs get()

查看:88
本文介绍了Django Queryset和filter()vs get()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

filter和get之间有什么区别

What is the Difference between filter and get

    >>> Question.objects.filter(id=1)
    <QuerySet [<Question: What's new?>]>
    >>> Question.objects.get(pk=1)
    <Question: What's new?>


推荐答案

区别在于过滤器返回一个queryset对象,即wheras get返回所需的对象。

The difference is that filter returns a queryset object, wheras get returns the required object.

如果使用filter(),通常只要期望的对象不止一个符合条件的对象,就会执行此操作。如果找不到符合您条件的项目,则filter()返回一个空查询集,而不会引发错误。

If you use filter(), you typically do this whenever you expect more than just one object that matches your criteria. If no item was found matching your criteria, filter() returns am empty queryset without throwing an error.

如果使用get(),则期望一个(只有一个) )符合您条件的项目。如果该项目不存在或存在多个符合您的条件的项目,则Get引发错误。因此,应始终尝试在..除了..块之外使用或与get_object_or_404之类的快捷功能一起使用,以便正确处理异常。

If you use get(), you expect one (and only one) item that matches your criteria. Get throws an error if the item does not exist or if multiple items exist that match your criteria. You should therefore always use if in a try.. except .. block or with a shortcut function like get_object_or_404 in order to handle the exceptions properly.

这篇关于Django Queryset和filter()vs get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆