如何在CVB的`get_context_data`中获得'pk'或'id'?

use*_*589 18 django django-class-based-views

如何get_context_data从CVB DetailView中获取'pk'或'id' ?

class MyDetail(DetailView):
    model = Book
    template_name = 'book.html'

    def get_context_data(self, **kwargs):
            context = super(MyDetail, self).get_context_data(**kwargs)
            context['something'] = Book.objects.filter(pk=pk)
            return context
Run Code Online (Sandbox Code Playgroud)

网址:

url(r'^book/(?P<pk>\d+)/$', MyDetail.as_view(), name='book'),
Run Code Online (Sandbox Code Playgroud)

Dan*_*man 36

你可以从中得到它self.kwargs['pk'].

我不确定你为什么要这么做,因为超类已经得到了对应于那个pk的Book - 这就是DetailView的重点.


rag*_*ghu 6

class MyDetail(DetailView):
    model = Book
    template_name = 'book.html'

    def get_context_data(self, **kwargs):
            context = super(MyDetail, self).get_context_data(**kwargs)
            context['something'] =Book.objects.filter(pk=self.kwargs.get('pk'))
            return context
Run Code Online (Sandbox Code Playgroud)


C.K*_*.K. 6

self.kwargs['pk'] 它在 Django 2.2 中不起作用

在详细视图中

self.object 是此视图正在显示的对象。

因此,要访问对象的字段,例如idpk只是self.object.idself.object.pk

所以,Django 2.2 中的答案可能是这样的:

class MyDetail(DetailView):
    model = Book
    template_name = 'book.html'

    def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context['something'] = Book.objects.filter(pk=self.object.pk)    # <<<---
            return context
Run Code Online (Sandbox Code Playgroud)

Django 2.2 文档


wav*_*der 5

在 get_context_data 中,您已经在 self.object 中拥有该对象(并且您可以执行 self.object.pk )。以下是类层次结构上游发生的情况(DetailView 继承自 BaseDetailView):

class BaseDetailView(SingleObjectMixin, View):
"""
A base view for displaying a single object
"""
def get(self, request, *args, **kwargs):
    self.object = self.get_object()
    context = self.get_context_data(object=self.object)
    return self.render_to_response(context)
Run Code Online (Sandbox Code Playgroud)

阅读 Django 源代码来理解内容非常容易。

顺便说一句,我不确定你是否总是可以信赖 kwargs 有一个“pk”密钥这一事实。