Ticket #7672: dayofweek_filter.r7875.r4.diff

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

Force oracle to use American format week day (i.e. Sunday=1)

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

     
    152152                    params)
    153153        elif lookup_type in ('range', 'year'):
    154154            return ('%s BETWEEN %%s and %%s' % field_sql, params)
    155         elif lookup_type in ('month', 'day'):
     155        elif lookup_type in ('month', 'day', 'week_day'):
    156156            return ('%s = %%s' % connection.ops.date_extract_sql(lookup_type,
    157157                    field_sql), params)
    158158        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

     
    233233        if hasattr(value, 'as_sql'):
    234234            sql, params = value.as_sql()
    235235            return QueryWrapper(('(%s)' % sql), params)
    236         if lookup_type in ('exact', 'regex', 'iregex', 'gt', 'gte', 'lt', 'lte', 'month', 'day', 'search'):
     236        if lookup_type in ('exact', 'regex', 'iregex', 'gt', 'gte', 'lt', 'lte', 'month', 'day', 'week_day', 'search'):
    237237            return [value]
    238238        elif lookup_type in ('range', 'in'):
    239239            return 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

     
    151151        dt = util.typecast_timestamp(dt)
    152152    except (ValueError, TypeError):
    153153        return None
    154     return str(getattr(dt, lookup_type))
     154    if lookup_type == 'week_day':
     155        return str((dt.isoweekday() % 7) + 1)
     156    else:
     157        return str(getattr(dt, lookup_type))
    155158
    156159def _sqlite_date_trunc(lookup_type, dt):
    157160    try:
  • django/db/backends/mysql/base.py

     
    6868class DatabaseOperations(BaseDatabaseOperations):
    6969    def date_extract_sql(self, lookup_type, field_name):
    7070        # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
    71         return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
     71        if lookup_type == 'week_day':
     72            # DAYOFWEEK() returns an integer, 1-7, Sunday=1.
     73            # Note: WEEKDAY() returns 0-6, Monday=0.
     74            return "DAYOFWEEK(%s)" % field_name
     75        else:
     76            return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
    7277
    7378    def date_trunc_sql(self, lookup_type, field_name):
    7479        fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
  • django/db/backends/oracle/base.py

     
    5656
    5757    def date_extract_sql(self, lookup_type, field_name):
    5858        # http://download-east.oracle.com/docs/cd/B10501_01/server.920/a96540/functions42a.htm#1017163
    59         return "EXTRACT(%s FROM %s)" % (lookup_type, field_name)
     59        if lookup_type == 'week_day':
     60            # TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday.
     61            return "TO_CHAR(%s, 'D')" % field_name
     62        else:
     63            return "EXTRACT(%s FROM %s)" % (lookup_type, field_name)
    6064
    6165    def date_trunc_sql(self, lookup_type, field_name):
    6266        # Oracle uses TRUNC() for both dates and numbers.
     
    216220                self.connection = Database.connect(conn_string, **self.options)
    217221            cursor = FormatStylePlaceholderCursor(self.connection)
    218222            # Set oracle date to ansi date format.  This only needs to execute
    219             # once when we create a new connection.
     223            # once when we create a new connection. We also set the Territory
     224            # to 'AMERICA' which forces Sunday to evaluate to a '1' in TO_CHAR().
    220225            cursor.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD' "
    221                            "NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'")
     226                           "NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF' "
     227                           "NLS_TERRITORY = 'AMERICA'")
    222228            try:
    223229                self.oracle_version = int(self.connection.version.split('.')[0])
    224230                # There's no way for the DatabaseOperations class to know the
  • tests/modeltests/basic/models.py

     
    6868<Article: Area woman programs in Python>
    6969>>> Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28)
    7070<Article: Area woman programs in Python>
     71>>> Article.objects.get(pub_date__week_day=5)
     72<Article: Area woman programs in Python>
    7173
    7274# The "__exact" lookup type can be omitted, as a shortcut.
    7375>>> Article.objects.get(id=1)
     
    8284>>> Article.objects.filter(pub_date__year=2005, pub_date__month=7)
    8385[<Article: Area woman programs in Python>]
    8486
     87>>> Article.objects.filter(pub_date__week_day=5)
     88[<Article: Area woman programs in Python>]
     89>>> Article.objects.filter(pub_date__week_day=6)
     90[]
     91
    8592# Django raises an Article.DoesNotExist exception for get() if the parameters
    8693# don't match any object.
    8794>>> Article.objects.get(id__exact=2)
     
    94101    ...
    95102DoesNotExist: Article matching query does not exist.
    96103
     104>>> Article.objects.get(pub_date__week_day=6)
     105Traceback (most recent call last):
     106    ...
     107DoesNotExist: Article matching query does not exist.
     108
    97109# Lookup by a primary key is the most common case, so Django provides a
    98110# shortcut for primary-key exact lookups.
    99111# The following is identical to articles.get(id=1).
  • docs/db-api.txt

     
    15341534Note this will match any record with a pub_date on the third day of the month,
    15351535such as January 3, July 3, etc.
    15361536
     1537week_day
     1538~~~~~~~~
     1539
     1540For date/datetime fields, a 'day of the week' match.
     1541
     1542Example::
     1543
     1544    Entry.objects.filter(pub_date__week_day=2)
     1545
     1546SQL equivalent::
     1547
     1548    SELECT ... WHERE EXTRACT('dow' FROM pub_date) = '2';
     1549
     1550(The exact SQL syntax varies for each database engine.)
     1551
     1552Note this will match any record with a pub_date that falls on a Tuesday (day 2
     1553of the week), regardless of the month or year in which it occurs. Week days
     1554are zero-indexed, with day 0 being Sunday and day 6 being Saturday.
     1555
    15371556isnull
    15381557~~~~~~
    15391558
Back to Top