Python列表视图-按相同的用户和日期获取和分组表数据

时间:2018-08-06 20:58:59

标签: python database listview

嗨。我正在开发Web应用程序,正在尝试编写一个列表视图,以从数据库中获取数据以创建统计表。

user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE)
created = models.DateTimeField(_('created'), auto_now_add=True, db_index=True)

我有一个名为 Activity 的对象,其中的 user ForeignKey ,而<< strong> created ”是< em> DateTimeField 。

在这里您可以看到我的列表视图代码:

class ActivityCountListView(LoginPermissionRequiredMixin, DisplayListViewMixin, SortingListViewMixin, ListView,):
model = Activity
permission_required = 'directory.list_activity'
displays = ['list', 'table']
paginate_values = [10, 50, 100]
paginate_by_display = {'table': paginate_values, 'list': paginate_values}
sorting_options = {'-created': _('Newest'), 'created': _('Oldest'), '-modified': _("Recently modified")}

def get_queryset(self):
    queryset = self.filter.qs.select_related('user')
    return self.sort_queryset(queryset)

def dispatch(self, request, *args, **kwargs):
    self.filter = ActivityFilter(request.user, request.GET, queryset=self.get_whole_queryset())
    return super(ActivityCountListView, self).dispatch(request, *args, **kwargs)

def get_whole_queryset(self):
    return Activity.objects.restrict_user(self.request.user)

def get_context_data(self, **kwargs):
    context_data = super(ActivityCountListView, self).get_context_data(**kwargs)
    context_data['filter'] = self.filter

    activities = Activity.objects \
        .annotate(day=ExtractDay('created'), month=ExtractMonth('created'), year=ExtractYear('created'))\
        .values('user', 'day', 'month', 'year') \
        .order_by('user')\

    data = self.get_data(activities)

    context_data.update({
        'data': data
    })

    return context_data

def get_data(self, activities):
    data = {}



    for activities_data in activities:
        print(activities_data)
        user = activities_data['user']
        day = activities_data['day']
        month = activities_data['month']
        year = activities_data['year']

        dt = datetime(year, month, day).date()
        formatted_date = str(dt)

        data.update({user: dict()})


        data[user][formatted_date] = 1


    print(data.keys())
    print(data.values())
    print(data)

    return data

使用此代码,我得到如下打印响应:

打印打印(活动数据):

{'user': 549, 'day': 24, 'month': 7, 'year': 2018}
{'user': 350, 'day': 24, 'month': 7, 'year': 2018}
{'user': 746, 'day': 31, 'month': 7, 'year': 2018}
{'user': 1, 'day': 31, 'month': 7, 'year': 2018}
{'user': 1, 'day': 24, 'month': 7, 'year': 2018}
{'user': 1, 'day': 24, 'month': 7, 'year': 2018}
{'user': 526, 'day': 31, 'month': 7, 'year': 2018}
{'user': 526, 'day': 24, 'month': 7, 'year': 2018}
{'user': 109, 'day': 24, 'month': 7, 'year': 2018}
{'user': 419, 'day': 24, 'month': 7, 'year': 2018}

打印(data.keys()):

dict_keys([549, 350, 746, 1, 526, 109, 419])

打印(data.values()):

dict_values([{'2018-07-24': 1}, {'2018-07-24': 1}, {'2018-07-31': 1}, {'2018-07-24': 1}, {'2018-07-24': 1}, {'2018-07-24': 1}, {'2018-07-24': 1}])

打印(数据):

{549: {'2018-07-24': 1}, 350: {'2018-07-24': 1}, 746: {'2018-07-31': 1}, 1: {'2018-07-24': 1}, 526: {'2018-07-24': 1}, 109: {'2018-07-24': 1}, 419: {'2018-07-24': 1}}

...但是不是我想要的,因为同一用户只有一个日期,没有活动计数 ...我希望得到答复像这样:

{549: {'2018-07-24': 1}, 350: {'2018-07-24': 1}, 746: {'2018-07-31': 1}, 1: {'2018-07-24': 2, '2018-07-31': 1,}, 526: {'2018-07-24': 1, '2018-07-31: 1}, 109: {'2018-07-24': 1}, 419: {'2018-07-24': 1}}

为了更好地理解: 如果同一用户有多个活动(例如用户ID 1):

{'user': 1, 'day': 31, 'month': 7, 'year': 2018}
{'user': 1, 'day': 24, 'month': 7, 'year': 2018}
{'user': 1, 'day': 24, 'month': 7, 'year': 2018}

我希望这样的数据响应:

1: {'2018-07-24': 2, '2018-07-31': 1,},

不是,就像这样:

1: {'2018-07-24': 1},

我真的不知道该怎么做。如果您能帮助我并将更改内容和代码内容写给我,我将非常高兴。...非常感谢

2 个答案:

答案 0 :(得分:1)

使用NAME , CATEGORY, SUBCATEGORY, RISK, TECHNOLOGY

itertools.groupby

答案 1 :(得分:0)

看起来像问题出在get_data()调用中。

代替此

data[user][formatted_date] = 1

可能需要编写如下内容

if formatted_date in data[user]:
   data[user][formatted_date] += 1
else
   data[user][formatted_date] = 1