Django:基于自定义函数过滤查询
我的 Django 模型类中内置了一个函数,我想使用该函数来过滤查询结果。
class service:
......
def is_active(self):
if datetime.now() > self.end_time:
return False
return True
现在我想在我的查询过滤器中使用这个函数,就像
nserv = service.objects.filter(is_active=True)
我知道的那样,对于这个简单的“is_active”情况,我可以直接在过滤器查询中进行比较,但对于更复杂的情况,这可能是不可能的。我应该如何根据自定义函数进行查询?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我刚刚遇到了类似的问题。问题是我必须返回一个 QuerySet 实例。对我来说,一个快速的解决方案是做这样的事情:
我很确定这不是最漂亮和最高效的方法,但它对我有用。
更详细的方法是:
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:
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:
我建议您为您的类使用自定义管理器,例如您可以使用:
nserv = service.objects.are_active()
这可以通过以下方式实现:< br>
请参阅自定义管理器
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:
See custom managers
您可能无法,相反,您可以使用 列表理解对查询集进行后处理 或 生成器表达式。
例如:
You may not be able to, instead you can post-process the queryset with a list comprehension or generator expression.
For example:
Ignacio 的答案很有趣,但它不返回查询集。这个的作用是:
The answer by Ignacio is interesting, but it does not return a queryset. This one does: