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“.
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')
- [Answered ]-How does the 'as' reserved word work in Django Template Language?
- [Answered ]-Django doesn't render the requested view
- [Answered ]-Why do I get a '403 (Forbidden)' error with Dajaxice?
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
- [Answered ]-How do I use context_instance in my template
- [Answered ]-How to setup PostGIS with an existing database?
- [Answered ]-Django ignore changed field in formset
- [Answered ]-Create Azure web site with Django and postgresql
Source:stackexchange.com