代码之家  ›  专栏  ›  技术社区  ›  Patrick Bond

如何将模型中的函数结果添加到列表中?

  •  1
  • Patrick Bond  · 技术社区  · 3 月前

    如何将模型中的函数结果添加到列表“subdom()”中

    models.py

    class Hromady(models.Model): ...
    
        def subdom(self):
            if self.alias:
                sub = self.alias
            else:
                sub = self.code.lower()
            return sub
    

    views.py

    def index(request):
        hromads = Hromady.objects.all()
        for hr in hromads:
            print(hr.subdom()) # ok
    
        hrom = hromads.annotate(obj_count=Count('object', filter=Q(object__state=1)))
        map_hrom = list(hrom.values('region', 'district', 'locality', 'type', *****subdom()*****???, 'obj_count'))
    
    1 回复  |  直到 3 月前
        1
  •  1
  •   Serhii Fomenko    3 月前

    您不能在中引用模型的方法 .values 。但你可以用另一个来写类似的表达式 .annotate 然后在中引用它 .values 。它看起来像这样:

    from django.db.models import (
        Case,
        Count,
        F,
        Q,
        When,
        functions,
    )
    
    queryset = (
        Hromady.objects
        .annotate(obj_count=Count('object', filter=Q(object__state=1)))
        .annotate(
            subdom=Case(
                When(~Q(alias=''), then=F('alias')),
                default=functions.Lower(F('code'))
            )
        )
        .values('region', 'district', 'locality', 'type', 'subdom', 'obj_count')
    )