How to return multiple objects related with ForeignKey in Django

岁酱吖の 提交于 2019-11-30 20:10:10

You can query on related objects like so:

manager = Managers.objects.get(pk=1) # identify which manager you want
manager.hostdata_set.all()  # retrieve all related HostData objects

In your template, you can also just access the hostdata_set directly:

{% for manager in managers %}
    {% for data in manager.hostdata_set.all %}
      do something with {{ data }}
    {% endfor %}
{% endfor %}

I believe this is what you're asking for.

Incidentally, if your Managers model stores data about a single "Manager", you may find it useful to change it's name to the singular Manager.

It seems that you want to ask the HostData to return all objects that are related to a certain Manager. If so, then you should know one unique piece of information about the certain Manager you are looking for.

For the sake of argument, let's assume the Manager "id" is used as a primary key and therefore unique and we are looking for a id = 5.

id = 5
hostdata = HostData.objects.filter(Manager__id=id)

I think (maybe??) you are looking for something like...

managers = Managers.objects.all()
host_data = HostData.objects.filter( managers__in=managers )

Then you can do looping inside the view?

I'm not exactly so sure this will work but let me know if it helps.

Just add host data sets dinamically to the template context:

def get_data(request):
 host_data_sets = []

 for server in Managers.objects.all():
    host_data_set = HostData.objects.filter(Manager=server)
    host_data_sets.append(host_data_set)

 return render_to_response('mypage.html', {'host_data_sets': host_data_sets})

Then in your template you can iterate over the data sets:

{% for host_data_set in host_data_sets %}
  <!-- do something with host_data_set -->
{% endfor %}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!