假设我有两个模型以多对多关系连接。
class Bar(models.Model):
name = models.CharField()
class Foo(models.Model):
name = models.CharField()
bars = models.ManyToManyField(Bars, through='FooBars')
class FooBars(models.Model):
date = models.DateTimeField(auto_now_add=true)
foo = models.ForeignKey(Foo, on_delete=models.CASCADE)
bar = models.ForeignKey(Bar, on_delete=models.CASCADE)
在
Foo
的查询集中,我想要相关的 Bars
按 date
排序,以便我可以根据 Foo
中按日期排序的名称的组合字符串对 bars
模型进行排序。
例如:
FooBars
:
富 | 酒吧 | 日期 |
---|---|---|
a | 阿尔法 | 2020年1月1日 |
a | 测试版 | 2020年1月3日 |
a | 伽玛 | 2020年1月2日 |
b | 阿尔法 | 2020年1月1日 |
b | 测试版 | 2020年1月2日 |
b | 伽玛 | 2020年1月3日 |
QuerySet 按
Foo.bars
的组合字符串排序:
福 | 酒吧 |
---|---|
b | 阿尔法、贝塔、伽马 |
a | α、γ、β |
我尝试过使用
Subquery
、F()
的某些组合进行注释,但无法让注释进行评估并显示在查询集中。
如果您使用 PostgreSQL,您可以执行以下操作:
from django.contrib.models.functions import StringAgg
from django.db.models import F, Q
res_val = Foo.objects.annotate(ordered_vals=StringAgg('bars__foobars__bar__name', ',', ordering='bars__foobars__date', filter=Q(bars__foobars__foo__name=F('name')))).values('name', 'ordered_vals')
StringAgg文档参考