r/django•
kyonz

Question on filtering foreign key data

I'm new to django so please don't hurt me too much, loving it but can't find a way around my current issue.

I have the following models (removed excess fields for brievity):

class server(models.Model):
    name = models.CharField(max_length=30)

class schedule(models.Model):
    start_time = models.DateTimeField()
    server = models.ForeignKey(server, related_name='schedules', on_delete=models.CASCADE)

Within my ListView I want to gather all servers, but only the schedules within that which have a start_time greater than the current time.

If I put a filter on get_queryset it appears to filter the server objects out (which makes sense but isn't what I want), and I can't appear to just itterate the schedules and pop them out from get_context_data as the objects are unsubscriptable.

Is anyone able to shed some light on what direction I should be going for this? I can remove offending schedules in the template but it just seems wrong.

Posted Dec 30, 2015, 12:36 AM UTC

14
crunching_karma•

If you want to get all servers that have schedules with start_time greater than the current time:

Server.objects.filter(schedule__start_time__gt=datetime.datetime.now()).distinct()

If you want all servres and for every server prefetch schedules that has start_time greater than current time:

Server.objects.prefetch_related(Prefetch('schedules', queryset=Schedule.objects.filter(start_time__gt=datetime.datetime.now()), to_attr='filtered_schedules'))

Now you should be able to access already filtered schedules for every server:

for s in servers:
    print s.filtered_schedules
2
kyonzOP•

So I tried this earlier and it appears to filter and only return server objects of which have a start_time greater than now - not all server objects with a subset of schedules.

Any ideas, below is how I applied it in case I'm being stupid.

class server_list(ListView):
    model = server

    def get_queryset(self):
        return server.objects.filter(schedules__start_time__gte=datetime.now()).distinct()
1
kyonzOP•

Thank you soo much, the prefetch_related line was exactly what I was struggling to find.

You just made my day! Thanks.

1
crunching_karma•

You are welcome, I am happy to help.

P.S Wow, thank you (:

1