2
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

Why does the "was_published_recently" method take self as a parameter? surely pub_date without the "self." would work fine

Edited title for clarity

Mascros
  • 341
  • 1
  • 3
  • 12

4 Answers4

3

No. pub_date without the self would cause a NameError, as it would be referencing a local or global variable which doesn't exist.

pub_date is an attribute of the model instance, and can only be referenced via self.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

There is no class method in your listing, only an ordinary method.

In either case, python methods (other than staticmethods) take a self parameter representing the object they are called on. Or to be more specific, the first parameter will be passed the self object, so you cannot decline to define a self parameter, only give it a different name.

More details on classmethods here: When should I use @classmethod and when def method(self)?

Community
  • 1
  • 1
Marcin
  • 48,559
  • 18
  • 128
  • 201
0

self changes the attribute of the instance of an object. If you want a class method, this cannot change or access the attributes of a specific variable. If pub_date does not change, then you can make it a class variable and add @classmethod above was_published_recently. Then, change the self to cls

rassa45
  • 3,482
  • 1
  • 29
  • 43
  • Sorry I didn't realise classmethod was a thing of its own, I meant class method as in the method of this class. – Mascros Jul 11 '15 at 17:00
  • Class method is basically an ordinary Python method except you have to call it like `Question.method()` in this case – rassa45 Jul 11 '15 at 17:02
0

You can't call the method was_published_recently() without a Question instance i.e. self.

pub_date is a field of the model Question and without any model instance, it does not hold any value in it as it would just be a variable. You won't be able to get a value by calling the function was_published_recently() as it would not have the value of pub_date for performing the necessary computation.

So to call the method was_published_recently(), you will have to pass the instance to this method or directly call on an instance using . operator.

Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126