我有一个类似Python的字典数组
{'district': u'd1', 'community': u'commu2', 'month': 8.0, 'county': u'c1', 'year': 2012.0, 'organization': u'org1'}
{'district': u'd2', 'community': u'commu8', 'month': 9.0, 'county': u'c1', 'year': 2012.0, 'organization': u'org2'}
{'district': u'd1', 'community': u'commu4', 'month': 9.0, 'county': u'c1', 'year': 2012.0, 'organization': u'org1'}
{'district': u'd2', 'community': u'commu5', 'month': 8.0, 'county': u'c1', 'year': 2012.0, 'organization': u'org2'}
{'district': u'd2', 'community': u'commu7', 'month': 9.0, 'county': u'c1', 'year': 2012.0, 'organization': u'org2'}
{'district': u'd1', 'community': u'commu3', 'month': 9.0, 'county': u'c1', 'year': 2012.0, 'organization': u'org1'}
{'district': u'd2', 'community': u'commu6', 'month': 8.0, 'county': u'c1', 'year': 2012.0, 'organization': u'org2'}
{'district': u'd1', 'community': u'commu1', 'month': 8.0, 'county': u'c1', 'year': 2012.0, 'organization': u'org1'}
我如何按多个键值分组,比如(地区、月份、年份、组织)并生成这样的非规范化列表?在
^{pr2}$编辑:我的数据库表感兴趣的列是
DISTRICT, COMMUNITY, DATE, ORGANIZATION, COMMUNITY
我使用Django的ORM来获取格式为1的数据,但我确实需要格式为2的数据
我的Django ORM抓取看起来像这样
list(ActivityReport.objects.all().
values('date').\
extra(select={'year': "EXTRACT(year FROM date)"}).\
extra(select={'month': "EXTRACT(month FROM date)"}).\
values('organization' ,'year','month', 'district', 'community'))
我的Django模型看起来像这样
class MyModel(models.Model):
organization = models.CharField(max_length=200)
district = models.CharField(max_length=200)
community = models.CharField(max_length=200, null=True)
date = models.DateField(default=datetime.date.today)
在我们的discussion in chat之后,我们知道这里还有一些附加的约束:传入的数据是这种格式的,它按原样保存到数据库中,并且建议的解决方案是在视图处理期间迭代它,以便在将其提供给用户之前对其进行按摩。在
如果社区是一个外键关系,那么从性能角度来说,最好是反映出它是一对多的关系,因此这可能不是最具伸缩性的解决方案。注意事项,我建议:
这里的想法是使用一对一的数据作为元组,元组是不可变的,因此可以作为dict键,然后创建一个从该元组到社区列表的映射。如果映射已经存在,则将其附加到列表中,否则创建它。一次通过后,数据如图所示。在
如果存在其他一对多的关系,希望这种技术可以适用于实际的数据集甚至其他列表。在
相关问题 更多 >
编程相关推荐