3

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

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

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

Any help would be great!

2
  • You need to research how to write filter queries first; that's not valid Django at all. Commented Feb 26, 2016 at 18:09
  • I tried to solve this problem on my on. I found this documantation: docs.djangoproject.com/en/1.9/howto/custom-management-commands I found a few errors I made but no solution to my problem.I would really appreciate help! Commented Feb 26, 2016 at 20:01

1 Answer 1

7

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Can you give me a hint for the filter? The basic idea was, that timestamp is the creationdate and the user can pick how long the post should last. The timestamp comes from a DateTimeField and duration from a tupel of Durationfield.
I posted some hints, to annotate the value with an F expression and then filtering by it, that should do it. If you run into issues please post your model fields and I'll make actual code for it tomorrow!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.