Django : Filter query based on custom function

前端 未结 4 1165
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 08:01

I\'ve got a function built into my Django model class and I want to use that function to filter my query results.

  class service:
       ......
       def i         


        
4条回答
  •  眼角桃花
    2020-12-09 08:12

    I just had a similar issue. The problem was i had to return a QuerySet instance. A quick solution for me was to do something like:

    active_serv_ids = [service.id for service in Service.objects.all() if service.is_active()]
    nserv = Service.objects.filter(id__in=active_serv_ids)
    

    pretty sure this is not the prettiest and performant way to do this, but i works for me.

    a more verbose way of doing this would be:

    active_serv_ids = []
    
    for service in Service.objects.all():
    if service.is_active():
        active_serv_ids.append(service.id)
    
    nserv = Service.objects.filter(id__in=active_serv_ids)
    

提交回复
热议问题