How to filter using an expression in Django

北城以北 提交于 2019-12-05 21:07:56
bakkal

Filter

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

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/en/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

Management Command

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()

More details: https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!