Reputation: 2064
I have a small probleme concerning django querysets and select_related.
With this model :
class DeviceGroup(models.Model):
name = models.CharField(max_length=255, unique=True)
owner = models.ForeignKey(User)
class Device(models.Model):
name = models.CharField(max_length=255)
address = models.GenericIPAddressField()
port = models.IntegerField()
group = models.ForeignKey(DeviceGroup)
class Sensor(models.Model):
device = models.ForeignKey(Device)
I'd like to get a list like :
- group 1
- device 1
- device 2
- device 3
-sensor 1
- group 2
- group 3
- device 4
- device 5
- sensor 2
I've read the doc about select_related(), but I don't know how to do because I've to start my query bu group cause, it's directly linked to logged user.
Upvotes: 1
Views: 1033
Reputation: 2064
is it possible to optimize or change my model. If i can't query it, it's maybe a model problem and not a queryset problem :)
Upvotes: 0
Reputation: 4318
If you want to present it this way in a Django template, you probably want to use regroup
:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup
The new docs is slightly more obfuscate, I find the old docs version easy to comprehend (this eg from https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#regroup ):
{% regroup people by gender as gender_list %}
<ul>
{% for gender in gender_list %}
<li>{{ gender.grouper }}
<ul>
{% for item in gender.list %}
<li>{{ item.first_name }} {{ item.last_name }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
Where in your case:
from view.py
group = Group.objects.all()
template.html
{% regroup groups by device as device_list %}
Upvotes: 1