[Answered ]-Django left join

2👍

You can use code like the following:

s = Server.objects.get(id=1)
cmdinfo = s.commandinfo_set.all()

Which would return a list of all CommandInfo objects that have s set as the foreign key.

You can get more info at the Django docs, “Following Relationships Backward“.

👤mipadi

0👍

Sometimes the Django ORM needs the left join field name to be explicitly name with select_related().

This is just off the top of my head so you’ll probably need to tweak it, but try something like:

s = Server.objects.select_related('commandinfo_set')

0👍

commands_by_server_id = defaultdict(list)
for c in CommandInfo.objects.select_related('server'):
  commands_by_server_id[c.server.id].append(c)

servers = Server.objects.all()
for s in servers:
  s.commands = commands_by_server_id.get(s.id, [])

Please note that you need to get the servers list due you can servers without CommandInfo

Leave a comment