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!

bakkal
  • 54,350
  • 12
  • 131
  • 107
Kaesekante
  • 109
  • 1
  • 9
  • You need to research how to write filter queries first; that's not valid Django at all. – Daniel Roseman Feb 26 '16 at 18:09
  • I tried to solve this problem on my on. I found this documantation: https://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! – Kaesekante Feb 26 '16 at 20:01

1 Answers1

6

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/

millerdev
  • 10,011
  • 2
  • 31
  • 27
bakkal
  • 54,350
  • 12
  • 131
  • 107
  • 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. – Kaesekante Feb 26 '16 at 19:58
  • 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! – bakkal Feb 26 '16 at 22:04