Janik Spies
Janik Spies

Reputation: 427

Django: Get a list of all related objects in models.py

it's a stupid question but i'm new to django and I didn't find a answer so far.

I'm trying to get a list of all related Years in the get_savings function. Don't look at the attributes of Year and Plan. They all exist.
The focus is on the For loop. I also tried for year in self.year_set.all: but it didn't work either.

models.py

class Plan(models.Model):
    title = models.CharField(max_length=50)
    ...

    @property
    def get_saving(self):
        delta: timedelta = now() - self.date_created
        months_gone = delta.days / 30
        saving = 0
        for year in Year.objects.all():
            if months_gone > year.months:
                saving = saving + year.savings_year
            else:
                saving = saving + months_gone * year.income_month
        return saving


class Year(models.Model):
    title = models.IntegerField()
    plan = models.ForeignKey(Plan, on_delete=models.CASCADE)

Upvotes: 0

Views: 75

Answers (1)

Sayse
Sayse

Reputation: 43330

self.year_set.all() is what you need.

all is a function so you need to call it rather than just reference it.

Upvotes: 2

Related Questions