1

我有两个模型父,子

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()))
4

1 回答 1

1
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()
    )
)
于 2021-06-18T07:54:58.717 回答