python - 示例使用查询集而不是 DetailView 扩展类的模型属性

标签 python django

在 django 文档页面上,针对 DetailView 类解释了 get_object 方法。他们使用此代码片段作为示例:

from django.utils import timezone
from django.views.generic import DetailView
from books.models import Author
class AuthorDetailView(DetailView):

    queryset = Author.objects.all()

    def get_object(self):
        obj = super().get_object()
        # Record the last accessed date
        obj.last_accessed = timezone.now()
        obj.save()
        return obj

Here's the link 。 我不明白的是为什么使用 queryset 属性以及为什么他们从数据库加载作者的所有对象。代码不应该是 模型 = Author.objects.get(pk=self.pk) ? 考虑到它不是 ListView 而是详细 View

最佳答案

简而言之:super().get_object()将正确执行.get()关于queryset属性。

Shouldn't the code be model = Author.objects.get(pk=self.pk)? Considering it's not a ListView but a DetailView.

已经完成了。标准get_object() SingleObjectMixin的方法将过滤 queryset您使用主键和/或 slug 定义,并返回该对象。您可以在source code [GitHub]中检查此方法。 。虽然真正的方法有点复杂(因为你可以配置 pkslug 字段的名称),但它基本上可以归结为:

# <i>over</i>simplified version!

class SingleObjectMixin(ContextMixin):
    # …

    def get_object(self, queryset):
        return self.get_queryset().get(
            pk=self.kwargs['pk'],
            slug=self.kwargs['slug']
        )

所以你在这里要做的就是创建一个 super().get_object()调用将对 queryset 进行正确的过滤,然后对 get_object() 检索到的对象进行一些修改方法。

why they are loading all objects of the Author from the database.

他们没有加载任何Author根本没有对象。 QuerySet我们很懒。这意味着只要您不“消耗”查询集,它就不会对数据库进行查询。通过使用.get(..)您将进行查询,但只有一个带有过滤器,因此(通常)检索一条记录。

关于python - 示例使用查询集而不是 DetailView 扩展类的模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59375022/

相关文章:

python - 如何在 Pygame 中设置 Pong 的碰撞检测

python - django Rest 框架 - XML 格式化

python - 异常值 : 'DatabaseWrapper' object has no attribute 'Database'

python - TypeError : the JSON object must be str, 不是 'DetailedResponse'

python - 使用子进程发送键盘事件

python - 如何切片张量的一部分?

python - 使用 Python 远程控制(轻量级)浏览器

python - 如何使用 Python 获取我的计算机可以看到的所有 WLAN 的列表?

javascript - 打开 Paypal 数字商品灯箱

django - Numpy 运行时警告导致 Apache Worker 卡住在 "Sending Reply"状态