Home > database >  Is it possible to return blank strings in .values() from a Django queryset?
Is it possible to return blank strings in .values() from a Django queryset?

Time:03-13

In Django, if I have 2 models:

class MyModelA(models.Model):
    column_1 = ...
    column_2 = ...
    column_3 = ...

class MyModelB(models.Model):
    column_1 = ...
    column_2 = ...
    column_3 = ...
    column_4 = ...
    column_5 = ...

I need to use union to combine the results in these, but they don't have the same number of columns. For the extra columns, I just need MyModelA to return blank strings.

Is it possible to do something like this?

MyModelA.objects.values("column_1", Value(""), Value(""), "column_2", "column_3").union(
    MyModelB.objects.values("column_1", "column_2", "column_3", "column_4", "column_5")
)

From the docs on union

Passing different models works as long as the SELECT list is the same in all QuerySets (at least the types, the names don’t matter as long as the types are in the same order)

This means I'm basically trying to map:

MyModelA.column_1 --> MyModelB.column_1
""                --> MyModelB.column_2
""                --> MyModelB.column_3
MyModelA.column_2 --> MyModelB.column_4
MyModelA.column_3 --> MyModelB.column_5

Using Value("") as above doesn't work however. Is there another way to do this?

CodePudding user response:

from django.db.models import F, Value

MyModelA.objects.values("column_1", column_2=Value(""), column_3=Value(""), column_4=F("column_2"), column_5=F("column_3")).union(
    MyModelB.objects.values("column_1", "column_2", "column_3", "column_4", "column_5")
)

You might not even need F as names might not clash in your case with real column names.

  • Related