user9252255
user9252255

Reputation:

Django: Why is self. used here?

I was just looking into Dynamic Filtering on the official documentation: https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-display/#dynamic-filtering

It says there

def get_queryset(self):
    self.publisher = get_object_or_404(Publisher, name=self.kwargs['publisher'])
    return Book.objects.filter(publisher=self.publisher)

Does anyone know, why for self.publisher = get_object_or_404, there was used self. at the beginning? I learned it so far that you don't add self. when defining the variable.

Specifically what I am not sure about now is if I should either use that code here:

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

Or that one:

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

Upvotes: 3

Views: 472

Answers (1)

Levi Moreira
Levi Moreira

Reputation: 12005

By using self here:

def get_queryset(self):
    self.publisher = get_object_or_404(Publisher, name=self.kwargs['publisher'])
    return Book.objects.filter(publisher=self.publisher)

We're declaring a class level variable that can be used by other methods in this class. That means we can use the variable by calling:

self.publisher

Anywhere in the class.

Upvotes: 3

Related Questions