Django sorting by date(day)

2024/10/2 3:28:14

I want to sort models by day first and then by score, meaning I'd like to see the the highest scoring Articles in each day.

class Article(models.Model):date_modified = models.DateTimeField(blank=True, null=True)
score = models.DecimalField(max_digits=5, decimal_places=3, blank=True, null=True)

This answer Django Datetime Field Query - Order by Time/Hour suggests that I use '__day' with my date_modified as in:

Article.objects.filter().order_by('-date_modified__day', '-score')
FieldError: Cannot resolve keyword 'day' into field. Join on 'date_modified' not permitted.

However I get the same error as in the post, so I'm not even sure it should work this way.

I found other answers django order by date in datetime / extract date from datetime using .extra:

Article.objects.filter().extra(select={"day_mod": "strftime('%d', date_modified)"}, order_by=['-day_mod', '-score'])

This works for filtering with no other conditions, but if I apply a condition on the filter such as a category:

Article.objects.filter(category = 'Art').extra(select={'day_mod': "strftime('%d', date_modified)"}, order_by=['-day_mod', '-score'])

I get this error:

File "/home/mykolas/anaconda2/lib/python2.7/site-packages/IPython/core/formatters.py", line 699, in __call__
printer.pretty(obj)File "/home/mykolas/anaconda2/lib/python2.7/site-packages/IPython/lib/pretty.py", line 383, in pretty
return _default_pprint(obj, self, cycle)File "/home/mykolas/anaconda2/lib/python2.7/site-packages/IPython/lib/pretty.py", line 503, in _default_pprint
_repr_pprint(obj, p, cycle)File "/home/mykolas/anaconda2/lib/python2.7/site-packages/IPython/lib/pretty.py", line 694, in _repr_pprint
output = repr(obj)File "/home/mykolas/lenv/lib/python2.7/site-packages/django/db/models/query.py", line 234, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])File "/home/mykolas/lenv/lib/python2.7/site-packages/django/db/models/query.py", line 258, in __iter__
self._fetch_all()File "/home/mykolas/lenv/lib/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())File "/home/mykolas/lenv/lib/python2.7/site-packages/django/db/models/query.py", line 52, in __iter__
results = compiler.execute_sql()File "/home/mykolas/lenv/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql
cursor.execute(sql, params)File "/home/mykolas/lenv/lib/python2.7/site-packages/django/db/backends/utils.py", line 83, in execute
sql = self.db.ops.last_executed_query(self.cursor, sql, params)File "/home/mykolas/lenv/lib/python2.7/site-packages/django/db/backends/sqlite3/operations.py", line 146, in last_executed_query
return sql % paramsTypeError: %d format: a number is required, not unicode

Don't really know what's going on here, help would be appreciated.

Answer
from django.db.models import DateTimeField
from django.db.models.functions import TruncArticle.objects.order_by(Trunc('date_modified', 'date', output_field=DateTimeField()).desc(),'-score')
  • Trunc() (Django 1.10)
  • order_by()
https://en.xdnf.cn/q/70896.html

Related Q&A

ImportError: No module named pynotify. While the module is installed

So this error keeps coming back.Everytime I try to tun the script it returns saying:Traceback (most recent call last):File "cli.py", line 11, in <module>import pynotify ImportError: No …

business logic in Django

Id like to know where to put code that doesnt belong to a view, I mean, the logic.Ive been reading a few similar posts, but couldnt arrive to a conclusion. What I could understand is:A View is like a …

Faster alternatives to Pandas pivot_table

Im using Pandas pivot_table function on a large dataset (10 million rows, 6 columns). As execution time is paramount, I try to speed up the process. Currently it takes around 8 secs to process the whol…

How can I temporarily redirect the output of logging in Python?

Theres already a question that answers how to do this regarding sys.stdout and sys.stderr here: https://stackoverflow.com/a/14197079/198348 But that doesnt work everywhere. The logging module seems to …

trouble with creating a virtual environment in Windows 8, python 3.3

Im trying to create a virtual environment in Python, but I always get an error no matter how many times I re-install python-setuptools and pip. My computer is running Windows 8, and Im using Python 3.3…

Python imaplib search email with date and time

Im trying to read all emails from a particular date and time. mail = imaplib.IMAP4_SSL(self.url, self.port) mail.login(user, password) mail.select(self.folder) since = datetime.strftime(since, %d-%b-%Y…

cumsum() on multi-index pandas dataframe

I have a multi-index dataframe that shows the sum of transactions on a monthly frequency. I am trying to get a cumsum() on yearly basis that respects my mapid and service multi-index. However I dont kn…

Python SSL Certification Problems in Tensorflow

Im trying to download the MNIST data which is supposedly handled in: tensorflow.examples.tutorials.mnist.input_data.read_data_sets() As far as Im aware read_data_sets sends a pull request to a server t…

How do I get a python program to run instead of opening in Notepad?

I am having some trouble with opening a .py file. I have a program that calls this .py file (i.e. pathname/example.py file.txt), but instead of running the python program, it opens it in Notepad. How t…

How to find a keys value from a list of dictionaries?

How do I get a given keys value from a list of dictionaries? mylist = [{powerpoint_color: blue,client_name: Sport Parents (Regrouped)},{sort_order: ascending,chart_layout: 1,chart_type: bar} ]The numb…