Ticket #7672: dayofweek_filter.r9097.r5.diff

File dayofweek_filter.r9097.r5.diff, 8.5 KB (added by Ross Poulton, 16 years ago)

Updated to work on Django 1.0 (SVN rev 9097)

  • django/db/models/sql/where.py

     
    162162                    params)
    163163        elif lookup_type in ('range', 'year'):
    164164            return ('%s BETWEEN %%s and %%s' % field_sql, params)
    165         elif lookup_type in ('month', 'day'):
     165        elif lookup_type in ('month', 'day', 'week_day'):
    166166            return ('%s = %%s' % connection.ops.date_extract_sql(lookup_type,
    167167                    field_sql), params)
    168168        elif lookup_type == 'isnull':
  • django/db/models/sql/constants.py

     
    44QUERY_TERMS = dict([(x, None) for x in (
    55    'exact', 'iexact', 'contains', 'icontains', 'gt', 'gte', 'lt', 'lte', 'in',
    66    'startswith', 'istartswith', 'endswith', 'iendswith', 'range', 'year',
    7     'month', 'day', 'isnull', 'search', 'regex', 'iregex',
     7    'month', 'day', 'week_day', 'isnull', 'search', 'regex', 'iregex',
    88    )])
    99
    1010# Size of each "chunk" for get_iterator calls.
  • django/db/models/fields/__init__.py

     
    196196        if hasattr(value, 'as_sql'):
    197197            sql, params = value.as_sql()
    198198            return QueryWrapper(('(%s)' % sql), params)
    199         if lookup_type in ('regex', 'iregex', 'month', 'day', 'search'):
     199        if lookup_type in ('regex', 'iregex', 'month', 'day', 'week_day', 'search'):
    200200            return [value]
    201201        elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
    202202            return [self.get_db_prep_value(value)]
  • django/db/backends/postgresql/operations.py

     
    2626
    2727    def date_extract_sql(self, lookup_type, field_name):
    2828        # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
    29         return "EXTRACT('%s' FROM %s)" % (lookup_type, field_name)
     29        if lookup_type == 'week_day':
     30                       # Using EXTRACT(), PostgreSQL days are indexed as Sunday=0, Saturday=6.
     31                       # If we instead us TO_CHAR, they're indexed with Sunday=1, Saturday=7
     32                       return "TO_CHAR(%s, 'D')" % field_name
     33        else:
     34            return "EXTRACT('%s' FROM %s)" % (lookup_type, field_name)
    3035
    3136    def date_trunc_sql(self, lookup_type, field_name):
    3237        # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
  • django/db/backends/sqlite3/base.py

     
    183183        dt = util.typecast_timestamp(dt)
    184184    except (ValueError, TypeError):
    185185        return None
    186     return unicode(getattr(dt, lookup_type))
     186    if lookup_type == 'week_day':
     187        return unicode((dt.isoweekday() % 7) + 1)
     188    else:
     189        return unicode(getattr(dt, lookup_type))
    187190
    188191def _sqlite_date_trunc(lookup_type, dt):
    189192    try:
  • django/db/backends/mysql/base.py

     
    115115class DatabaseOperations(BaseDatabaseOperations):
    116116    def date_extract_sql(self, lookup_type, field_name):
    117117        # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
    118         return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
     118        if lookup_type == 'week_day':
     119            # DAYOFWEEK() returns an integer, 1-7, Sunday=1.
     120            # Note: WEEKDAY() returns 0-6, Monday=0.
     121            return "DAYOFWEEK(%s)" % field_name
     122        else:
     123            return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
    119124
    120125    def date_trunc_sql(self, lookup_type, field_name):
    121126        fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
  • django/db/backends/oracle/base.py

     
    6767
    6868    def date_extract_sql(self, lookup_type, field_name):
    6969        # http://download-east.oracle.com/docs/cd/B10501_01/server.920/a96540/functions42a.htm#1017163
    70         return "EXTRACT(%s FROM %s)" % (lookup_type, field_name)
     70        if lookup_type == 'week_day':
     71            # TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday.
     72            return "TO_CHAR(%s, 'D')" % field_name
     73        else:
     74            return "EXTRACT(%s FROM %s)" % (lookup_type, field_name)
    7175
    7276    def date_trunc_sql(self, lookup_type, field_name):
    7377        # Oracle uses TRUNC() for both dates and numbers.
     
    253257                self.connection = Database.connect(conn_string, **self.options)
    254258            cursor = FormatStylePlaceholderCursor(self.connection)
    255259            # Set oracle date to ansi date format.  This only needs to execute
    256             # once when we create a new connection.
     260            # once when we create a new connection. We also set the Territory
     261            # to 'AMERICA' which forces Sunday to evaluate to a '1' in TO_CHAR().
    257262            cursor.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD' "
    258                            "NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'")
     263                           "NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF' "
     264                           "NLS_TERRITORY = 'AMERICA'")
    259265            try:
    260266                self.oracle_version = int(self.connection.version.split('.')[0])
    261267                # There's no way for the DatabaseOperations class to know the
  • tests/modeltests/basic/models.py

     
    7474<Article: Area woman programs in Python>
    7575>>> Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28)
    7676<Article: Area woman programs in Python>
     77>>> Article.objects.get(pub_date__week_day=5)
     78<Article: Area woman programs in Python>
    7779
    7880# The "__exact" lookup type can be omitted, as a shortcut.
    7981>>> Article.objects.get(id=1)
     
    8890>>> Article.objects.filter(pub_date__year=2005, pub_date__month=7)
    8991[<Article: Area woman programs in Python>]
    9092
     93>>> Article.objects.filter(pub_date__week_day=5)
     94[<Article: Area woman programs in Python>]
     95>>> Article.objects.filter(pub_date__week_day=6)
     96[]
     97
    9198# Django raises an Article.DoesNotExist exception for get() if the parameters
    9299# don't match any object.
    93100>>> Article.objects.get(id__exact=2)
     
    100107    ...
    101108DoesNotExist: Article matching query does not exist.
    102109
     110>>> Article.objects.get(pub_date__week_day=6)
     111Traceback (most recent call last):
     112    ...
     113DoesNotExist: Article matching query does not exist.
     114
    103115# Lookup by a primary key is the most common case, so Django provides a
    104116# shortcut for primary-key exact lookups.
    105117# The following is identical to articles.get(id=1).
  • docs/ref/models/querysets.txt

     
    11681168Note this will match any record with a pub_date on the third day of the month,
    11691169such as January 3, July 3, etc.
    11701170
     1171week_day
     1172~~~~~~~~
     1173
     1174For date/datetime fields, a 'day of the week' match.
     1175
     1176Example::
     1177
     1178    Entry.objects.filter(pub_date__week_day=2)
     1179
     1180SQL equivalent::
     1181
     1182    SELECT ... WHERE EXTRACT('dow' FROM pub_date) = '2';
     1183
     1184(The exact SQL syntax varies for each database engine.)
     1185
     1186Note this will match any record with a pub_date that falls on a Monday (day 2
     1187of the week), regardless of the month or year in which it occurs. Week days
     1188are indexed with day 1 being Sunday and day 7 being Saturday.
     1189
    11711190isnull
    11721191~~~~~~
Back to Top