0

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>
Kritz
  • 7,099
  • 12
  • 43
  • 73
  • is there something on ModalA that you are filtering on? I'm thinking _set is going to help you out. https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward – AMG Jan 04 '17 at 16:59
  • Yes, it is actually a single instance of ModelA, but even if I use modelx_set.all() and modely_set.all() I'm still stuck with two querysets. Or am I missing something? – Kritz Jan 04 '17 at 17:02
  • queryset is just with sql statement `SELECT FROM...` behind the scene, so there's no way that you could `SELECT` from 2 tables in the same statement, thus there's no way to have "one merged queryset". But you could have a list of objects for `ModelX` and `ModelY`. What result are you trying to achieve? – Shang Wang Jan 04 '17 at 17:04
  • I was thinking that if you needing to combine for a template purposes only, then you could use one of the solutions at http://stackoverflow.com/questions/6217638/access-foreignkey-set-directly-in-template-in-django Depends completely of course on what you are displaying (assuming the question has been simplified for clarity). – AMG Jan 04 '17 at 17:07
  • do you have any sample data, and what you want displayed? – AMG Jan 04 '17 at 17:08
  • I've added an example how it will be used in the template. If I don't merge the two querysets into one then I need to loop over the two querysets individually and it then gets tricky to build the table. This method works, but my guess is that it is a common problem and there must be a better/cleaner way? – Kritz Jan 04 '17 at 17:30

0 Answers0