【问题标题】:Django dynamic filtered ListView returning error: get() got multiple values for argument 'self'Django 动态过滤 ListView 返回错误:get() 为参数“self”获取了多个值
【发布时间】:2021-03-22 05:30:19
【问题描述】:

我需要一些帮助来解决这个问题。我想我正在执行 django 文档 (https://docs.djangoproject.com/en/3.1/topics/class-based-views/generic-display/) 的建议,但我不断收到此错误:get() got multiple values for argument 'self'

textbook_list.html

<a href="{% url 'lesson_list' textbook.pk %}">
    <button type="button" class="btn btn-info">More Info</button>
</a>

urls.py

urlpatterns = [path('grade/<int:pk>/', TextbookLessonList.as_view(), name='lesson_list')]

views.py

class TextbookLessonList(ListView):
    template_name = 'textbook_lesson_list.html' 

    def get_queryset(self):
        self.textbook = get_object_or_404(Textbook, self=self.kwargs['pk']) #This is the offending line
        return TextbookLesson.objects.filter(textbook.pk==self.textbook)

【问题讨论】:

    标签: django django-views django-templates django-generic-views


    【解决方案1】:

    使用self=…没有多大意义,你要在主键上过滤,所以:

    class TextbookLessonList(ListView):
        template_name = 'textbook_lesson_list.html' 
    
        def get_queryset(self):
            self.textbook = get_object_or_404(Textbook, pk=self.kwargs['pk'])
            return TextbookLesson.objects.filter(textbook=self.textbook)

    但你本身并不需要访问教科书,如果你只对TextbookLessons感兴趣,你可以直接过滤:

    class TextbookLessonList(ListView):
        template_name = 'textbook_lesson_list.html'
        model = TextbookLesson
    
        def get_queryset(self, *args, **kwargs):
            return super().get_queryset(*args, **kwargs).filter(
                textbook_id=self.kwargs['pk']
            )

    【讨论】:

    • 你是神,先生。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2010-12-28
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2023-01-28
    • 1970-01-01
    相关资源
    最近更新 更多