2

I'm making a blog-like platform which includes an event page. I have a model as below:

class Event(models.Model):
    dtime_start = models.DateTimeField(null=False, blank=False)
    dtime_end = models.DateTimeField(null=False, blank=False)

Assuming I have a view called event_main which projects all events. However, I want to project currently active events at the top of page, highlighted. So what I need is:

  1. to get exact request datetime of client
  2. to filter Event instances having the request datetime between dtime_start and dtime_end

I thought of solutions including for loops and put the results in the list, however I don't really want to put model instances to a list, since there are QuerySets. Is there a built-in way to do this in Django?

###############
# Environment #
###############
python 3.2.5
pypy 2.4.0
django 1.8.7
Eray Erdin
  • 2,633
  • 1
  • 32
  • 66

2 Answers2

4

To get the request datetime of the client, you may :

  1. Rely on the "Date" header (request.META.get('HTTP_DATE')),
  2. Rely on the current date of the server and the client timezone
  3. Fallback to the current date of the server

Then you can filter with common lookups as you would to for an integer:

Event.objects.filter(dtime_start__lte=request_datetime,
                     dtime_end__gte=request_datetime)

Note: Unless you have some specific reasons to rely on the client's date, you should probably avoid it and simply use datetime.now() or timezone.now() (both would work the same, as Django handles timezone conversion when dealing with the database). If you rely on the client's date, beware that they could temper with the Date header to access past or future events.

Antoine Pinsard
  • 33,148
  • 8
  • 67
  • 87
1

The dtime_start <= input AND dtime_end >= output:

Event.objects.filter(dtime_start__lte=datetime.date(y, m, d), dtime_start__gte=datetime.date(y, m, d))

For more information, refer to the documentation.

jhoepken
  • 1,842
  • 3
  • 17
  • 24
nlgn
  • 378
  • 3
  • 13