我正在尝试在我的model.manager中使用kwarg field='unanswered=True'
,但它正在抱怨许多值要解压缩。不理解为什么以及如何处理它。
模特经理:
class ListAllObjectsManager(models.Manager):
def date_search_threads(self, date1, date2, **kwargs):
print kwargs["field"]
date1 = datetime.datetime.strptime(date1, "%m-%d-%Y").date()
date2 = datetime.datetime.strptime(date2, "%m-%d-%Y").date()
date2 = date2 + datetime.timedelta(days=1)
return super(ListAllObjectsManager, self).get_queryset().filter(
kwargs["field"], **{'{}__range'.format(
kwargs["column"]): (date1, date2)})
查看:
class StatisticsView(LoginRequiredMixin, TemplateView):
template_name = 'bot_data/stats.html'
def get_context_data(self, **kwargs):
date1 = self.request.GET.get('search')
date2 = self.request.GET.get('search_extra')
if not date1 or not date2:
date1 = "12-01-1999"
date2 = "12-01-2050"
context['unanswered_threads'] = ThreadVault.list_all_threads \
.date_search_threads(date1, date2, field='unanswered=True',
column="latest_post_date").count()
return context
答案 0 :(得分:1)
我认为这是因为kwargs["field"]
只是一个字符串。试试
def date_search_threads(self, date1, date2, **kwargs):
print kwargs["field"]
date1 = datetime.datetime.strptime(date1, "%m-%d-%Y").date()
date2 = datetime.datetime.strptime(date2, "%m-%d-%Y").date()
date2 = date2 + datetime.timedelta(days=1)
param_filter = {'{}__range'.format(kwargs["column"]): (date1, date2)}
if 'field' in kwargs:
field = kwargs['field'].split('=')
param_filter[field[0]] = field[1]
return super(ListAllObjectsManager, self).get_queryset().filter(**param_filter))
或者更好的是,直接在kwargs中传递一个词典:
...
context['unanswered_threads'] = ThreadVault.list_all_threads \
.date_search_threads(date1, date2, field={'unanswered': True},
column="latest_post_date").count()
和
...
param_filter = {'{}__range'.format(kwargs["column"]): (date1, date2)}
param_filter.update(kwargs.get('field', {})
return super(ListAllObjectsManager, self).get_queryset().filter(**param_filter))