2014-05-21 42 views
0

我想在我的model.manager使用kwarg field='unanswered=True'但它抱怨許多值來解壓。不理解爲什麼以及如何處理它。的Django 1.6 models.Manager抱怨很多價值觀解壓

型號經理:

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 

回答

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))