django - Django 的 filter() 和 get() 方法的区别

标签 django

之间有什么区别

mymodel=model.objects.get(name='pol')


mymodel=model.objects.filter(name='pol')

最佳答案

Django QuerySet docs对此非常清楚:
get(**kwargs)¶

Returns the object matching the given lookup parameters, which should be in the format described in Field lookups.

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.


filter(**kwargs)

Returns a new QuerySet containing objects that match the given lookup parameters.



基本使用get()当你想得到一个唯一的对象 , 和 filter()当你想得到所有对象 匹配您的查找参数。

关于django - Django 的 filter() 和 get() 方法的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3221938/

相关文章:

python - Django HStore : How to override a key-value model field's __getattr__ and __setattr__

python - 如何在虚拟环境中使用源码安装Django?

django - 如何通过 uwsgi 强制应用程序的标准输出日志?

python - 如何跨子模块导入

python - 无法加载资源: the server responded with a status of 403 (Forbidden) django framework

django - 如何在 Django Rest Framework 的自定义字段中传递额外的关键字参数?

python - @staff_member_required 正在抛出 "object has no attribute ' 用户'”

django - 发送电子邮件时需要转义字符吗?

django - 对 EC2 进行基准测试

python - django 仅在满足特定条件时才将数据保存在数据库中