Michael Smith
Michael Smith

Reputation: 3447

Expiration logic with DateTimeField in Django

I have a DateTimeField in a Service model defined like this:

pub_date = models.DateTimeField(default=timezone.now,blank=True)

I want to create some expiration logic in my code so that Services that are older than 2 months expire. In my view, only those services that aren't expired will be displayed.

For example I want to do this in a view:

views.py

class display_services:
    services = Service.objects.all()
    valid_services = []
    for service in service
        **If Service is Not Expired***
              valid_services.append(service)
    endfor
...

Upvotes: 2

Views: 3358

Answers (2)

dylrei
dylrei

Reputation: 1738

I think this is what you want:

import datetime as dt
two_months_ago = dt.date.today() + dt.timedelta(days=-60)
valid_services = Service.objects.filter(pub_date__gte=two_months_ago)

Upvotes: 1

Ngenator
Ngenator

Reputation: 11259

You can just filter by pub_date

from datetime import datetime, timedelta

class DisplayServices(ListView):
    queryset = Service.objects.filter(pub_date__gte=datetime.now()-timedelta(days=60))

    ...

Upvotes: 3

Related Questions