Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

python - Django : Filter query based on custom function

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 is_active(self):
            if datetime.now() > self.end_time:
                  return False
            return True

Now I want to use this function into my query filter, something like

nserv = service.objects.filter(is_active=True)

I know, for this simple 'is_active' case, I can directly make this comparision in filter query, but for more complex situations, that may not be possible. How should I make a query, based on custom functions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 this:

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

I'm pretty sure this is not the prettiest and performant way to do this, but it 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...