我有两个模型Parent,Child
class Parent(models.Model):
id = models.IntegerField(...)
class Child(models.Model)
id = models.IntegerField(...)
parent = models.ForeignKey(Parent, ...)
wanted = models.CharField(default="yes")
我有一个查询集
parents = Parent.objects.all()
我想将一个字符字段注释到基于子模型的父查询集
get_status(obj):
# complex function which returns string based on child onjects
children = Child.objects.filter(parent_id = obj.id)
if children.count() == 1:
return 'some'
if children.count() == 2:
return 'thing'
我想要这样的东西,如何将对象发送到get_status((函数。
queryset.annotate(status = Value(get_status(), output_field=CharField()))
from django.db.models import Count, Case, When, Value, CharField
Parent.objects.annotate(
children=Count('child')
).annotate(
status=Case(
When(children__gte=2, then=Value('thing')),
When(children=1, then=Value('some')),
output_field=CharField()
)
)