tadalendas
tadalendas

Reputation: 1541

Djangosum two fields from different tables

I use the code below to sum fields in different tables. However, when there's no record that matches table1_id in table2, django returns None

Table 1
id    val
1     2
2     3

Table 2
id    val    table1_id
1     5      1

The query below would return:

7
None

How would I return:

7
3

Django query:

SomeModel.objects.filter(
    some_filters
).annotate(
    var=ExpressionWrapper(
        F('val') + F('table2__val'), output_field=FloatField()
    )
)

Upvotes: 0

Views: 39

Answers (1)

tadalendas
tadalendas

Reputation: 1541

using Coalesce from django.db.models.functions solved my issue

SomeModel.objects.filter(
    some_filters
).annotate(
    var=ExpressionWrapper(
        F('val') + Coalesce(F('table2__val'), 0), output_field=FloatField()
    )
)

Upvotes: 1

Related Questions