我有两个型号: 猫(id、名字) CatRecords(id、cat_id、状态、创建时间)
每天,一只猫都会有一条关于该猫状态的记录
我想获取所有的猫以及每只猫的最新记录,按记录的created_time排序 我可以获取每只猫的所有记录,但无法获取每只猫的最新记录
Cat的查询类:
class Query(graphene.ObjectType):
all_cats = graphene.List(CatType)
cat = graphene.Field(CatType, cat_id=graphene.UUID())
latest_record = graphene.Field(CatRecordType)
def resolve_all_cats(self, info, **kwargs):
cats = Cat.objects.all()
return cats
def resolve_cat(self, info, cat_id):
return Cat.objects.get(cat_id=cat_id)
def resolve_latest_record(self, info):
subquery = CatRecord.objects.filter(cat_id=OuterRef("id")).order_by(
"-created_time"
)
return (
Cat.objects.all()
.annotate(latest_record=Subquery(subquery.values("id")[:1]))
.values("latest_record")
)
我的询问
query {
latestRecord{
id
name
}
}
错误是
{
"errors": [
{
"message": "Received incompatible instance \"<QuerySet [{'latest_record': UUID('3d2af716-94aa-4952-9050-4d7f69384e3d')}, {'latest_record': UUID('0705aeda-a2ec-47c3-8bd1-1aa445c40444')}]>\".",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"latestRecord"
]
}
],
"data": {
"latestRecord": null
}
}
FilteredRelation
[Django-doc]:
Cat.objects.annotate(
latest_record=FilteredRelation(
'catrecords_set',
condition=Q(
pk=Subquery(
CatRecords.objects.filter(cat_id=OuterRef('pk'))
.order_by('-created_time')
.values('pk')[:1]
),
),
),
).select_related('latest_record')
然后,这将为每个
CatRecords
获取最新的 Cat
并将其添加为 .latest_record
,否则添加为 None
。
注意:通常 Django 模型会被赋予一个 singular 名称 [django-antipatterns],所以
而不是CatRecord
。CatRecords