简体   繁体   English

Django objects.filter vs objects.all

[英]Django objects.filter vs objects.all

I have a question regarding the filter() and all() methods of django objects.我对 django 对象的 filter() 和 all() 方法有疑问。 It is not a question which one of the two is preferred, I just noticed an odd (to me) behavior.这不是两个更喜欢哪一个的问题,我只是注意到一个奇怪的(对我来说)行为。 Because, as it is laid out in因为,正如它在

Django ORM - objects.filter() vs. objects.all().filter() - which one is preferred? Django ORM - objects.filter() 与 objects.all().filter() - 哪个更受欢迎?

in Django src, both ways should return the same (they both reference the chain() method):在 Django src 中,两种方式都应该返回相同的(它们都引用了 chain() 方法):

See:看:

https://github.com/django/django/blob/0963f184abd96800b76b19a6a181e1b544c7fafe/django/db/models/query.py#L928 https://github.com/django/django/blob/0963f184abd96800b76b19a6a181e1b544c7fafe/django/db/models/query.py#L928

And:和:

https://github.com/django/django/blob/0963f184abd96800b76b19a6a181e1b544c7fafe/django/db/models/query.py#L951 https://github.com/django/django/blob/0963f184abd96800b76b19a6a181e1b544c7fafe/django/db/models/query.py#L951

So the filter() and all() method should return the same objects.所以 filter() 和 all() 方法应该返回相同的对象。 But I recently discovered the following behavior:但我最近发现了以下行为:

MyModel.objects.all()[0].update(name="Test")

# --> $: AttributeError: type object 'MyModel' has no attribute 'update'

# And to check if it indeed has no update method:

MyModel.objects.all[0].__dir__() # --> no update() method in returned dictionary but a save method

So while above code raises Error, line below would work:因此,虽然上面的代码引发了错误,但下面的行会起作用:

MyModel.objects.all()[0].name = "Test"
MyModel.objects.all()[0].save()

However, if the same object is retrieved by the filter() method, it has the update() method.但是,如果通过 filter() 方法检索到相同的 object,则它具有 update() 方法。

Why do I get the same object both times but with seemingly different methods added to it?为什么我两次都得到相同的 object 但添加了看似不同的方法?

the update() function is only on the Manager object. update() function 仅在管理器 object 上。 Looking at your comments, you are effectively called MyModel.objects.filter(name="Test").update(name="test2") which is a valid queryset function.查看您的评论,您实际上被称为MyModel.objects.filter(name="Test").update(name="test2")这是一个有效的查询集 function。 If you used MyModel.objects.get(name="Test") which would be the same as the all() version.如果您使用MyModel.objects.get(name="Test")这将与all()版本相同。

In your all() example, you are working on the model, which lacks an update() function.在您的all()示例中,您正在处理 model,它缺少update() function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM