我想过滤实现这个“伪代码”:
Post.objects.filter(Post.timestamp + Post.duration > datetime.datetime.now())
我还想将它包装在 Django 管理命令中。
任何帮助都会很棒!
我想过滤实现这个“伪代码”:
Post.objects.filter(Post.timestamp + Post.duration > datetime.datetime.now())
我还想将它包装在 Django 管理命令中。
任何帮助都会很棒!
不确定您的字段的外观,但这里有一个提示:
让我们像这样组成一个F 表达式F('timestamp') - F('duration')
,并用它来注释我们的查询:
from django.db.models import DateTimeField, ExpressionWrapper, F
Post.objects.annotate(
timestamp_minus_duration=ExpressionWrapper(
F('timestamp') + F('duration'),
output_field=DateTimeField()
)
)
现在您可以使用该带注释的字段进行过滤
Post.objects.annotate(
timestamp_minus_duration=ExpressionWrapper(
F('timestamp') + F('duration'),
output_field=DateTimeField()
)
).filter(
timestamp_minus_duration__gt=datetime.datetime.now()
)
参考:https ://docs.djangoproject.com/en/1.9/topics/db/queries/#using-f-expressions-in-filters
参考:https ://docs.djangoproject.com/es/1.9/ref/models/expressions/#using-f-with-annotations
参考:https ://docs.djangoproject.com/es/1.9/topics/db/aggregation/#filtering-on-annotations
只需将代码放在handle()
命令的方法中即可
# 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/