Suppose I have two models in Django that is related to each other via a common model such as the example below:
class ModelA(models.Model):
f = models.IntegerField()
class ModelX(models.Model):
a = models.ForeignKey(ModelA)
x = models.FloatField()
class ModelY(models.Model):
a = models.ForeignKey(ModelA)
y = models.FloatField()
Now suppose I want to query ModelX and ModelY and merge the two querysets into a single queryset where their reference is equal to ModelA. What is the best way to achieve this?
What I've tried so far is building a dictionary with the one model and then looking it up when iterating over the second model, but I'm sure there must be a better way?
I typically need to do this when I'm building a html table and looping over the queryset.
m_x = ModelX.objects.all()
d = {}
for m in m_x:
d[m.a] = m.x
m_y = ModelY.objects.all()
for m in m_y:
m.x = d.get(m.a, 0)
I will then use it in the template as follows:
<table>
<tr>
<th>F</th>
<th>X</th>
<th>Y</th>
</tr>
{% for item in m_y %}
<tr>
<td>{{ item.a.f }}</td>
<td>{{ item.x }}</td>
<td>{{ item.y }}</td>
</tr>
{% endfor %}
</table>