Django queryset iteration

I need to iterate through the date entries and want compare them to other dates, but I get only one value, what am I doing wrong ?

    @property
    def mathe2(self):
        for i in self.lehrertabelle_set.all():
            return i.from_date

You can do something like this:

@property
def mathe2(self):
    date_list = []
    now = datetime.now()
    for i in self.lehrertabelle_set.all():
        if i.date == now:
            date_list.append(i)
    return date_list

return statement returns value and exits the method so no more values will be checked.

If you want to iterate through all of them and check something then use:

for i in self.lehrertabelle_set.all():
    if i.from_date == something:
        # do something

If you want to get a list of lehrertabelle in a given range then filter queryset using gte (greater then or equal) and lte (less then or equal):

qs_in_range = self.lehrertabelle_set.filter(from_date__gte=start_date, from_date__lte=end_date)

you can read more here: https://docs.djangoproject.com/en/4.1/ref/models/querysets/#field-lookups

sorry need to correct myself, joshlsullivan answer helped me solving my issue. after testing all through, I got the sum of everything when the date was the same on every value, and that was not my goal. I needed that every entry is compared to each other and based on true or false it calcs the trues together this is now my solution for that. But I thank everybody who helped me out!

  @property
    def mathe2(self):
        einzelne_werte = []
        for i in self.lehrertabelle_set.all():
            if i.von_Datum == self.Prognose_Datum:
                einzelne_werte.append(i.Stunden)
        return sum(einzelne_werte) / 28 

Back to Top