Question

How can use union and "not in" function in django query. I have searched on it but cannot find any example

SELECT id,address
    FROM tbl_nt
    WHERE st_id IN (1,2) AND name = 'foo'
    UNION (
        SELECT d.id,d.addrses
            FROM tbl_nt_123 d
            WHERE d.name='foo' AND condition_id NOT IN (
                SELECT condition_id 
                    FROM tbl_conditions
                    WHERE version_id = 5
            )
    )

i have tried this query for lower portion but didn't work

tbl_nt_123.objects.values_list('id', 'address').exclude(
    condition_id=tbl_conditions 
).objects.filter(version_id=5).values_list(
    'condition_id', flat=True)
)

How can i do this?

Please refer me some good links or books for understand advance django queries.

Thank you

Was it helpful?

Solution

Probably you should just add the __in lookup modifier:

tbl_nt_123.objects.values_list('id','address').exclude(
    condition_id__in=tbl_conditions.objects.filter(version_id=5).values_list('condition_id',flat=True))

As for the union, you can fake it using the | operator.

union = queryset1 | queryset2

OTHER TIPS

Django querysets now have a .union() method. Something like this:

tbl_nt.objects.filter(st_id__in=(1, 2), name='foo').union(
    tbl_nt.objects.filter(name='foo')
    .exclude(condition__in=Condition.objects.filter(version_id=5))
).values_list('id', 'address')

https://docs.djangoproject.com/en/stable/ref/models/querysets/#union

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top