问题描述
我有一个内置Django模型类的函数,我想使用该函数过滤查询结果。
类服务:
......
def is_active(self):
如果datetime.now()> self.end_time:
return False
return True
现在我要使用这个函数进入我的查询过滤器,像
nserv = service.objects.filter(is_active = True)
我知道,对于这个简单的is_active案例,我可以直接在过滤器查询中进行比较,但对于更复杂的情况,这可能是不可能的。我应该如何根据自定义函数进行查询?
我建议您为自己的课程使用自定义管理器,像这样你可以使用:
nserv = service.objects.are_active()
这可以通过以下方式实现:
class ServiceManager(models.Manager):
pre>
def are_active(self):
#使用你的方法过滤结果
return you_custom_queryset
请参阅
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?
解决方案I would suggest you to use a custom manager for your class, like this you could use :
nserv = service.objects.are_active()
This would be achieved with something like:
class ServiceManager(models.Manager): def are_active(self): # use your method to filter results return you_custom_queryset
See custom managers
这篇关于Django:根据自定义函数过滤查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!