【问题标题】:Annotate in django object using function使用函数在 django 对象中注释
【发布时间】:2021-09-02 23:07:38
【问题描述】:

我有两个模型 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()))

【问题讨论】:

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


    【解决方案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()
        )
    )
    

    【讨论】:

      猜你喜欢
      • 2016-02-27
      • 1970-01-01
      • 2017-07-09
      • 2020-03-14
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      • 1970-01-01
      相关资源
      最近更新 更多