You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django技术疑问:为何在get_queryset中使用self.定义变量?

Why use self. when assigning variables in Django class-based views?

Great question—this is a super common point of confusion when making the jump from function-based views to class-based ones. Let’s break this down in plain terms:

First, remember that in Python class methods, self refers to the live instance of your view class. When you assign a variable with self.variable_name, you’re creating an instance attribute that any other method in the same view instance can access later. Without self., the variable is just a local variable that dies as soon as the current method finishes running.

Let’s walk through your two options:

写法一 (Local Variable):

def get_queryset(self):
    slug = self.kwargs.get('slug')
    return Event.objects.filter(organiser__slug=slug)

This is totally valid if you only need the slug value inside the get_queryset method. Since you’re using it immediately to filter your queryset and don’t need it anywhere else, there’s no reason to store it as an instance attribute. This is clean, efficient, and the right call for this isolated use case.

写法二 (Instance Attribute):

def get_queryset(self):
    self.slug = self.kwargs.get('slug')
    return Event.objects.filter(organiser__slug=self.slug)

Here, you’re storing slug as an attribute on the view instance. The big advantage here is that other methods in your view (like get_context_data, which passes data to your template) can now access this value. For example, if you wanted to display the current organiser’s slug in your template, you could add:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['current_organiser_slug'] = self.slug
    return context

Why does the Django docs example use self.publisher?

In the dynamic filtering example, assigning self.publisher = get_object_or_404(...) makes sense because the view likely needs that Publisher object elsewhere. The template might want to show the publisher’s name, location, or other details—storing it as an instance attribute lets the get_context_data method pass it to the template without re-fetching the object from the database.

Final Takeaway:

  • Use local variables (no self.) when the value is only needed in the current method.
  • Use instance attributes (self.) when the value needs to be shared across multiple methods in the view.

Both of your code examples are correct—pick the one that fits your specific needs!

内容的提问来源于stack exchange,提问作者user9252255

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:02:04