#converting QuerySet to list in concise way for test purposes

30 messages · Page 1 of 1 (latest)

stark glade
#

Hello. I am stumbled over issue of correct assigning value to field with m2m relation.
So, in the essense I have such problem – how to convert in concise and clean way Queryset into list of ids of object from such Queryset
So, basic syntax I implemented now –

original_data['assignees'] = list(task.assignees.values_list('id', flat=True))[0],

looks very cumbersome and terrible.
Best option I discovered as of now it just do like this –

original_data['assignees'] = [worker1.id, worker2.id][0],

But it still looks strange and not good from my perspective.
So, could you please help me, how to do it in more clean and concise way?

bitter cairn
#

what is this trailing , ?

stark glade
stark glade
stark glade
craggy harness
#

task.assignees.values_list(“id”, flat=True) is a list

#

Well. Functions as one. You can call list on it, as you did above, if you must have it as an exact list type

stark glade
craggy harness
#

No, by “functions as a list” I mean the result of values_list works exactly like a list in the vast majority of places you would need it.

craggy harness
#

Why do you want other options?

stark glade
#

Because this one is not concise and clean

craggy harness
#

[x.id for x in task.assignees.all()] is another option, but less efficient.

stark glade
#

And I don't want to use dictionary key for assigning

craggy harness
stark glade
# craggy harness What?

This I don't want to use

original_data['assignees'] = task.assignees.values_list('id', flat=True)
craggy harness
#

Care to elaborate on why? Or just because you don’t feel like it?

#

I’m honestly a bit lost.

stark glade
craggy harness
#

Right, well as this is the first time you’re telling us you’re converting an object to a dictionary, it’s very difficult to follow what you’re asking

#

Why are you converting it to a dictionary, and how are you expecting Django to just automatically know that you want the IDs?

stark glade
craggy harness
#

Honestly, I think your entire approach to testing causes these weird problems.

#

Can you summarise, in one sentence, what exactly you're testing with this test case?

stark glade
stark glade
craggy harness
#

Isn't that what you fixed in the other question you posted?

#

My suggestion would probably be something along the lines of:

  1. Have a dictionary that describes the object you want to update
  2. Create that object in setUp or the test itself using the data in the dict
  3. Make a copy of the dict with the updated data you want
  4. Post that data to the endpoint
  5. Fetch the object and assert that the updates applied
#

There is no way around crafting a dictionary of data to send to the update endpoint. Thats literally how the API works, so that's what you need to do in the test.