0

设置

我有两张桌子:

姓名
蒂姆
汤姆

宠物 | 物种| 颜色 | |---------|--------| | 猫 | 黑色 | | 狗 | 棕色 |

还有一个连接它们的多对多:

人对宠物

人名 宠物种类
蒂姆
蒂姆
汤姆

期望的结果

使用 Django,我想注释 Person 以便我得到这个表:

人名 结果
蒂姆 <a>猫(黑色)</a><a>狗(棕色)</a>
汤姆 <a>猫(黑色)</a>

这可能吗?

我只有这个:

from django.contrib.postgres.aggregates import StringAgg


Person.objects.annotate(
    result=StringAgg('pets', delimiter=',')
)

这使:

人名 结果
蒂姆 猫狗
汤姆

谁能破解这个坚果?

4

1 回答 1

0

找到了解决方案:

from django.contrib.postgres.aggregates import StringAgg
from django.db.models.functions import Concat
from django.db.models import Case, Value, When, F, Value, CharField


Person.objects.annotate(
    result=StringAgg(
        Case(
            When(
                pets__isnull=False,
                then=Concat(
                    # <a>{species} ({color})\<a> 
                    Value('<a>'),
                    F('pet__species'),
                    Value(' ('),
                    F('pet__color'),
                    Value(')</a> '),
                    output_field=CharField()
                )
            )
        ),
        delimiter=''
    )
)
于 2021-06-10T19:50:03.170 回答