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
If you want to get all servers that have schedules with start_time greater than the current time:
If you want all servres and for every server prefetch schedules that has start_time greater than current time:
Now you should be able to access already filtered schedules for every server:
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.
Thank you soo much, the prefetch_related line was exactly what I was struggling to find.
You just made my day! Thanks.
You are welcome, I am happy to help.
P.S Wow, thank you (: