django model.objects.filter(mydate__month = date.today()。month)不工作

时间:2018-05-18 07:26:45

标签: django filter model django-queryset

我一直盯着这一点,但却看不到问题。基本上我有很多观点,并根据不同的日期组合进行过滤,例如今年,或本月甚至今天等等。我在这个月过滤了一个观点,过滤器。

对于当前年度过滤器,这有效:

queryset = mymodel.objects.filter(mydate__year=date.today().year).order_by('field')

但是,在当月尝试这种方法并不是:

queryset = mymodel.objects.filter(mydate__month=date.today().month).order_by('field')

抛出异常,基本上概括为:

TypeError at /core/tcCoreVendor/
not all arguments converted during string formatting

我可以通过以下方式解决这个问题:

month = date.today().month
where = "%(month)s = MONTH(mtime)" % {'month': month}
queryset = mymodel.objects.extra(where=[where])

但这看起来很疯狂!

非常感谢任何帮助或建议!

这是模特:

class tcCore_vendor(models.Model):
    '''
    tcCore_vendor

    Model that represents the vendors of hardware, software and applications etc.
    '''
    uid = models.CharField(db_column='uid', max_length=50, unique=True, primary_key=True, editable=False)
    name = models.CharField(db_column='name', max_length=50, blank=False, null=False)
    address = models.TextField(db_column='address', blank=True, null=True)
    contact = models.CharField(db_column='contactnumber', max_length=50, blank=True, null=True)
    image = models.TextField(db_column='image', blank=True, null=True)
    mtime = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    class Meta:
        managed = False
        app_label = 'tcCore'
        db_table = 'tc_core_vendor'
        ordering = ['name']

以下是观点:

class tcCore_vendor_viewset(viewsets.ModelViewSet):
    """
    API for viewing and editing vendors.
    """
    permission_classes = (permissions.IsAdminUser,)
    serializer_class = tcCore.serializers.tcCore_vendor_serializer
    search_fields = ('name', )
    ordering_fields = ('name',)

    def get_queryset(self):
        """ Override the standard query set to provide some flexibility on the result set. """

        view = self.request.query_params.get('view', None)
        if view is not None:
            if int(view) == 1: # Any date
                queryset = tcCore.models.tcCore_vendor.objects.all().order_by('name')
            elif int(view) == 2: # Today
                queryset = tcCore.models.tcCore_vendor.objects.filter(mtime__date=date.today()).order_by('name')
            elif int(view) == 3: # Past 7 days
                queryset = tcCore.models.tcCore_vendor.objects.filter(mtime__range=[timezone.now() - timedelta(days=7),  timezone.now()]).order_by('name')
            elif int(view) == 4: # This month
                queryset = tcCore.models.tcCore_vendor.objects.filter(mtime__month__lte=date.today().month).order_by('name')
            elif int(view) == 5: # This year
                queryset = tcCore.models.tcCore_vendor.objects.filter(mtime__year=date.today().year).order_by('name')
            else: # No view provided
                queryset = tcCore.models.tcCore_vendor.objects.all().order_by('name')
        else: # No view provided
            queryset = tcCore.models.tcCore_vendor.objects.all().order_by('name')

        return queryset

    def get_view_name(self):
        name = "tcCoreVendor"
        suffix = getattr(self, 'suffix', None)
        if suffix:
            name += ' ' + suffix
        return name

这里有完整的痕迹:

TypeError at /core/tcCoreVendor/
not all arguments converted during string formatting

Request Method: GET
Request URL: http://127.0.0.1:8000/core/tcCoreVendor/?view=4
Django Version: 2.0.2
Python Executable: /Users/xxxxxxxxxxx/anaconda3/envs/company_name/bin/python
Python Version: 3.6.5
Python Path: ['/Users/xxxxxxxxxxx/Google Drive/GitHub/company_name', '/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python36.zip', '/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6', '/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/lib-dynload', '/Users/xxxxxxxxxxx/.local/lib/python3.6/site-packages', '/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages']
Server time: Fri, 18 May 2018 08:23:17 +0000
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'corsheaders',
 'rest_framework',
 'rest_framework.authtoken',
 'django_filters',
 'raven.contrib.django.raven_compat',
 'tcCore.apps.tcCoreConfig']
Installed Middleware:
['raven.contrib.django.middleware.DjangoRestFrameworkCompatMiddleware',
 'raven.contrib.django.middleware.SentryMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'company_name.tcMiddleware.middleware']


Traceback:

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/core/paginator.py" in count
  85.             return self.object_list.count()

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/query.py" in count
  387.         return self.query.get_count(using=self.db)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/sql/query.py" in get_count
  491.         number = obj.get_aggregation(using, ['__count'])['__count']

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/sql/query.py" in get_aggregation
  476.         result = compiler.execute_sql(SINGLE)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1051.             sql, params = self.as_sql()

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in as_sql
  459.                 where, w_params = self.compile(self.where) if self.where is not None else ("", [])

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in compile
  391.             sql, params = node.as_sql(self, self.connection)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/sql/where.py" in as_sql
  80.                 sql, params = compiler.compile(child)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in compile
  391.             sql, params = node.as_sql(self, self.connection)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/lookups.py" in as_sql
  160.         lhs_sql, params = self.process_lhs(compiler, connection)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/lookups.py" in process_lhs
  155.             db_type, field_internal_type) % lhs_sql

During handling of the above exception (not all arguments converted during string formatting), another exception occurred:

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/rest_framework/viewsets.py" in view
  103.             return self.dispatch(request, *args, **kwargs)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  483.             response = self.handle_exception(exc)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
  443.             self.raise_uncaught_exception(exc)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  480.             response = handler(request, *args, **kwargs)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/rest_framework/mixins.py" in list
  42.         page = self.paginate_queryset(queryset)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/rest_framework/generics.py" in paginate_queryset
  173.         return self.paginator.paginate_queryset(queryset, self.request, view=self)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/rest_framework/pagination.py" in paginate_queryset
  204.             self.page = paginator.page(page_number)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/core/paginator.py" in page
  65.         number = self.validate_number(number)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/core/paginator.py" in validate_number
  43.         if number > self.num_pages:

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/utils/functional.py" in __get__
  36.         res = instance.__dict__[self.name] = self.func(instance)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/core/paginator.py" in num_pages
  95.         if self.count == 0 and not self.allow_empty_first_page:

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/utils/functional.py" in __get__
  36.         res = instance.__dict__[self.name] = self.func(instance)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/core/paginator.py" in count
  90.             return len(self.object_list)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/query.py" in __len__
  254.         self._fetch_all()

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/query.py" in _fetch_all
  1179.             self._result_cache = list(self._iterable_class(self))

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/query.py" in __iter__
  53.         results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1051.             sql, params = self.as_sql()

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in as_sql
  459.                 where, w_params = self.compile(self.where) if self.where is not None else ("", [])

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in compile
  391.             sql, params = node.as_sql(self, self.connection)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/sql/where.py" in as_sql
  80.                 sql, params = compiler.compile(child)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in compile
  391.             sql, params = node.as_sql(self, self.connection)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/lookups.py" in as_sql
  160.         lhs_sql, params = self.process_lhs(compiler, connection)

File "/Users/xxxxxxxxxxx/anaconda3/envs/company_name/lib/python3.6/site-packages/django/db/models/lookups.py" in process_lhs
  155.             db_type, field_internal_type) % lhs_sql

0 个答案:

没有答案