Andrew
Andrew

Reputation: 3999

Python/Django QuerySet to list of dicts?

This is my code:

obj = Object1.objects.get(pk=1)
other_objs = ob1.other_objs.all()

other_objs is a ManyToManyField on the Object1 object.

When I execute this code:

print other_objs[0]

I do not get an other_obj (which should be a dict), I get a string based off the __unicode__ method in the other_obj class.

How can I get the other_obj dict rather than just the unicode string?

Upvotes: 0

Views: 4157

Answers (2)

Anurag Uniyal
Anurag Uniyal

Reputation: 88727

other_objs[0] will be the first element of query and will not be a dict or string but the django model object, you can access attributes like other_objs[0].myattr1, if you want dict you can ask for specifc attributes using objects.values_list and then create a dict out of them e.g.

attrs = ['id', 'attr1']
values = Object1.objects.values_list(attrs)[0]
obj_dict = dict(zip(attrs, values))

or you can use django serialization is you want to output dict or json etc, but I think you just need an object, and original query is sufficient.

Upvotes: 4

juliomalegria
juliomalegria

Reputation: 24911

When you do .all(), you're getting a queryset (see it as a list) of the objects related with your Object1 object.

So, when you do other_objs[0], you're getting the first related object. And then, when you print it, it calls its __unicode__ method to actually print the object.

Upvotes: 0

Related Questions