views:

40

answers:

3

I have the following in my models.py:

class HostData(models.Model):
  Manager = models.ForeignKey(Managers)
  Host = models.CharField(max_length=50, null=True)
  HostStatus = models.CharField(max_length=200, null=True)
  Cpu = models.PositiveIntegerField(max_length=10, null=True)
  Disk = models.FloatField(null=True)

I would like to return the query for objects related to a certain "Manager". The problem is that the user may add/delete as many managers as he wants. So my initial thought was to have in my views.py something like this:

def get_data(request):
 for server in Managers.objects.all():
    host_data = HostData.objects.filter(Manager=server)
    # Lost after this :(
 return render_to_response('mypage.html', {'first_set': host_data1, 'second_set': host_data2})

So, how can I return multiple objects? Like if the user adds another "Manager" I'll get a third set in my views.py.

A: 

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.

meder
+2  A: 

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.

Seth
Thanks! this is what I was looking for. Just a note: Parentheses are not used in the template tags, so in the template it should be: manager.hostdata_set.all
Ping Pengũin
Thanks, that was a copy and paste error I think.
Seth
Funny.. I ended up needing the *exact* same thing just now. Thanks Seth.
meder
A: 

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 %}
marcelor