[Fixed]-How do I merge two queries in django and select distinct from two unrelated tables

1👍

You can use the extra() modifier to assign alternative names.

queryA = tableA.extra(select={'alias' : 'first_name_A'}).order_by('first_name_A').values('alias').distinct()
queryB = tableB.extra(select={'alias' : 'first_name_B'}).order_by('first_name_B').values('alias').distinct()

The django documentation discourages the use of extra but there doesn’t seem to be an easy way to create aliases in a queryset. This ticket suggest that this may change in the future. The last comment describes an alternative method with F expressions and annotate which should work with django v1.8

👤zxzak

0👍

I’ve solved it but I’m not sure it’s the most pythonic (nor correct) way. If anyone has any better suggestions then please let me know.

views.py

        queryA = tableA.objects.order_by('first_name_A','last_name_A').values('first_name_A', 'last_name_A').distinct()
        queryB = tableB.objects.order_by('first_name_B','last_name_B').values('first_name_B', 'last_name_B').distinct()


        chain_query = sorted(chain(queryA, queryB))


        valueList = []


        for q in chain_query:
            wholeName = ' '.join(q.values())
            valueList.append(wholeName)


        query = sorted(set(valueList))  

        return render_to_response('results.html', {'queries': query})

html

    {% for query in queries %}
    <tr>
        <td>{{ query }}</td>
    </tr>
    {% endfor %}

Leave a comment