Django 的 filter() 和 get() 方法的区别 [英] Difference between Django's filter() and get() methods
问题描述
有什么区别
mymodel=model.objects.get(name='pol')
和
mymodel=model.objects.filter(name='pol')
推荐答案
Django QuerySet 文档对此非常清楚:
get(**kwargs)¶
返回匹配给定的对象查找参数,应该在字段查找中描述的格式.
Returns the object matching the given lookup parameters, which should be in the format described in Field lookups.
get() 引发 MultipleObjectsReturned如果发现不止一个物体.这MultipleObjectsReturned 异常是模型类的一个属性.
get() raises MultipleObjectsReturned if more than one object was found. The MultipleObjectsReturned exception is an attribute of the model class.
get() 引发一个DoesNotExist 异常如果找不到对象给定参数.这个例外是也是模型类的一个属性.
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)
返回一个包含与给定查找参数匹配的对象的新 QuerySet.
Returns a new QuerySet containing objects that match the given lookup parameters.
当您想获得单个唯一对象时,基本上使用get()
,当您想获得时使用filter()
>与您的查找参数匹配的所有对象.
Basically use get()
when you want to get a single unique object, and filter()
when you want to get all objects that match your lookup parameters.
这篇关于Django 的 filter() 和 get() 方法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!