如何在Django中使用表达式进行过滤 [英] How to filter using an expression in Django

查看:161
本文介绍了如何在Django中使用表达式进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想过滤器来实现此伪代码":

I'd like to filter that implements this "pseudocode":

   Post.objects.filter(Post.timestamp + Post.duration > datetime.datetime.now())

我也想将其包装在Django管理命令中.

I also would like to wrap this in a Django management command.

任何帮助都会很棒!

推荐答案

过滤器

不确定字段的外观,但这是一个提示:

Filter

Not sure how your fields look but here's a hint:

让我们像这样的F('timestamp') - F('duration')组成一个 F表达式,并用它来注释我们的查询:

Let's compose an F expression like this F('timestamp') - F('duration'), and annotate our query with it:

from django.db.models import DateTimeField, ExpressionWrapper, F

Post.objects.annotate(
        timestamp_minus_duration=ExpressionWrapper(
            F('timestamp') + F('duration'),
            output_field=DateTimeField()
        )
    )

现在您可以使用带注释的字段进行过滤

Now you can filter with that annotated field

   Post.objects.annotate(
        timestamp_minus_duration=ExpressionWrapper(
            F('timestamp') + F('duration'),
            output_field=DateTimeField()
        )
    ).filter(
        timestamp_minus_duration__gt=datetime.datetime.now()
    )

ref: https://docs.djangoproject.com/zh-CN/1.9/topics/db/queries/#using-f-expressions-in-filters

ref: https://docs.djangoproject.com/es/1.9/ref/models/expressions/#using-f-with-annotations

ref: https://docs. djangoproject.com/es/1.9/topics/db/aggregation/#filtering-on-annotations

只需将代码放入命令的handle()方法中

Just put the code in the handle() method of the command

# yourapp/management/commands/deletepost.py

from django.core.management.base import BaseCommand, CommandError
from yourapp.models import Post

class Command(BaseCommand):
    help = 'Describe your cmd here'

    def handle(self, *args, **options):
           Post.objects.annotate(...).filter(...).delete()

更多详细信息: https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/

这篇关于如何在Django中使用表达式进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆