使用函数在 django 对象中进行注释

时间:2021-06-18 07:47:17

标签: django django-queryset django-annotate drf-queryset

我有两个模型父母,孩子

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

1 个答案:

答案 0 :(得分: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()
    )
)