[Answered ]-Django model dynamically query ManyToManyField for values

1👍

You can work with getattr(…) [Python-doc]:

getattr(my_book_model, 'references').values('f_name', 'l_name')

so getattr(x, 'y') is thus equivalent to x.y. You should however be careful: if an arbitrary string can be used, people might exploit this as a security vulnerability.

Furthermore the use of .values(…) [Django-doc] is often not a good idea either. One can use serializers to convert model objects to dictionaries. This article [Django-antipatterns] explains problems with using .values(…).

Leave a comment