I’d like to test the view that does the creation of a Thing where you select multiple users (among other details).
I defined a Thing model, having a “users” ManyToManyField to the User model (from Django’s shipped authentication app).
Here’s my test code :
class ViewsTest(TestCase):
def test_create(self):
my_users = [...some User instances...]
response = self.client.post("/create/", {...stuff...,
'users': [user.id for user in my_users]})
self.assertEqual(200, response.status_code)
created_thing = Thing.objects.get(...)
self.assertListEqual(my_users, [user for user in created_thing.users.all()])
This test passes, so all is well, but I’m annoyed by the list comprehension at the end. Isn’t there a more elegant way to get the created_thing.users as a list ?
I’m using Django 1.4.1.
List comprehension is a typical way to create a list from a django
querysetso what you did was perfectly fine.What @PuercoPop suggested is fine too – using
list(created_thing.users.all())because it forces the evaluation of thequerysetinto a list type object containing your user objects.