demux
demux

Reputation: 4654

django order by date in datetime / extract date from datetime

I have a model with a datetime field and I want to show the most viewed entries for the day today.

I thought I might try something like dt_published__date to extract the date from the datetime field but obviously it didn't work.

popular = Entry.objects.filter(type='A', is_public=True).order_by('-dt_published__date', '-views', '-dt_written', 'headline')[0:5]

How can I do this?

Upvotes: 6

Views: 3537

Answers (2)

pymen
pymen

Reputation: 6549

In the new Django, it should work out of the box [tested on 3.2] with Mysql 5.7

Dataset

[
  { "id": 82148, "paid_date": "2019-09-30 20:51:11"},
  { "id": 82315, "paid_date": "2019-09-30 00:00:00"},
]

Query

Payment.objects.filter(order_id=135342).order_by('paid_date__date', 'id').values_list('id', 'paid_date__date')

Results

`<QuerySet [(82148, datetime.date(2019, 9, 30)), (82315, datetime.date(2019, 9, 30))]>`

Upvotes: 1

Manoj Govindan
Manoj Govindan

Reputation: 74705

AFAIK the __date syntax is not supported yet by Django. There is a ticket open for this.

If your database has a function to extract date part then you can do this:

popular = Entry.objects.filter(**conditions).extra(select = 
    {'custom_dt': 'to_date(dt_published)'}).order_by('-custom_dt')

Upvotes: 12

Related Questions