0

I'm learning python, hence this is probably an obvious solution for some, but I am trying to create a class that, whenever created, has a test field with a date value of three months from now.

My class is as follows:

class Something(models.Model):
    test = models.DateTimeField(default=self.get_date())

    def get_date(self):
        today = datetime.date.today()
        return today + relativedelta(months=1)

I thought that I could define it as a function and then call it to set the date. Can someone advise what's wrong here? Any links to relevant documentation would also be appreciated, thank you.

user8758206
  • 2,106
  • 4
  • 22
  • 45
  • 1
    You can't use `self` when you're initializing a class-level attribute. That `get_date` method doesn't use `self` anyway, you could define it outside the class. – joanis Mar 17 '22 at 13:03

1 Answers1

0

If you want a subclass to have a specific attribute, like the "test field" you could define it in the parents class like so:

import models

class Class:
  test = models.DateTimeField() 

class Subclass(Class)
   

With this solution every "Sublass-Object" would have the attribute "test" in it when initialized.

W4tu
  • 1
  • 2