将类似字典的列表转换为包含列表的字典列表

时间:2017-08-03 09:51:36

标签: python django dictionary django-rest-framework

我使用django进行的查询得到了这个序列化数据(django rest framework),
我用作我项目的后端:

i_have = [
    {'product_name': 'Foo', 'role': 'aRole', 'user_name': 'foobar'},
    {'product_name': 'Foo', 'role': 'anotherRole', 'user_name': 'foobar'},
    {'product_name': 'Bar', 'role': 'aRole', 'user_name': 'foobar'},
    {'product_name': 'Bar', 'role': 'anotherRole', 'user_name': 'foobar'},
]

对于我的客户端,用JavaScript和React编写我想将数据转换为:

i_want = [
    {'product_name': 'Foo', 'roles': ['aRole', 'anotherRole'], 'user_name': 'foobar'},
    {'product_name': 'Bar', 'roles': ['aRole', 'anotherRole'], 'user_name': 'foobar'},
]

我目前正在使用与此类似的查询获取数据 (伪代码)

AUserProduct.objects.filter(user_name='foobar').order_by('product_name')

虽然我的模特基本上看起来像这样 (也是伪代码)

Product(models.Model):
    product_name = models.CharField(max_length=255)

AUser(models.Model):
    user_name = models.CharField(max_length=255)

AUserProduct(models.Model):
    product_name = models.ForeignKey('Product')
    user_name = models.ForeignKey('AUser')
    role = models.CharField(max_length=255, choices=('aRole', 'anotherRole'))

有没有办法用django查询实现这个目的?
如果我将角色放在一个单独的表中并将AUserProduct中的外键关系添加到角色表中,它会改变结果中的任何内容吗?
或者我是否必须遍历数据并选择角色并将其附加到包含所需角色列表的新词典中? 如果是这样,让客户端从服务器接收数据后,让服务器处理数据转换还是应该在我的React组件中进行转换会更好?

为了达到我想要的目的,这是我唯一想出的东西:

i_have = [
    {'product_name': 'Foo', 'role': 'aRole', 'user_name': 'foobar'},
    {'product_name': 'Foo', 'role': 'anotherRole', 'user_name': 'foobar'},
    {'product_name': 'Bar', 'role': 'aRole', 'user_name': 'foobar'},
    {'product_name': 'Bar', 'role': 'anotherRole', 'user_name': 'foobar'},
]


i_want = []
new_d = {'product_name': '', 'user_name': '', 'roles': []}
for d in i_have:
    if new_d['product_name'] != d['product_name']:
        new_d = {'user_name': d['user_name'], 'product_name': d['product_name'], 'roles': []}
    if new_d not in  i_want:
        i_want.append(new_d)
    new_d['roles'].append(d['role'])


print('-'*10)
for i in i_want:
    print(i)

但如果没有更好的方法来解决这个问题,我很好奇。 任何形式的帮助都表示赞赏 提前致谢

0 个答案:

没有答案
相关问题