0

I've got this serialized data (django rest framework) as a result from a query i made with django,
which i'm using as backend for my project:

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'},
]

For my client, written in JavaScript and React i would like to transform the data into:

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

I'm currently getting the data with a query which looks similar to this
(pseudocode)

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

while my models basically looks like this
(also pseudocode)

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

Is there any way of achieving this with a django query?
Would it change anything in the result if i put the roles in a seperate table and add a foreign key relationship from AUserProduct to the Role Table?
Or do i have to iterate through the data and pick the role and append it to a new dictionary which contains the desired list with roles?
And if so, would it be better to let the server handle the transformation of the data or should i transform it in my React Component, after the client received it from the server?

This was the only thing i could come up with in order to achieve what i want:

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)

But i'm curios if there isn't any better way to solve this. Any help in any kind is appreciated.
Thanks in advance

BigZ
  • 836
  • 8
  • 19

0 Answers0