Home > Net >  Django queryset iteration
Django queryset iteration

Time:09-10

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

CodePudding user response:

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

CodePudding user response:

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
  • Related