Home > Software design >  Django model dynamically query ManyToManyField for values
Django model dynamically query ManyToManyField for values

Time:06-22

The following code works fine for an object that has a ManyToManyField called references like this:

res = []
for ref in MyBook.objects.get(id=some_id).references.values("f_name", "l_name"):
    res.append(ref)

My question is, how can I dynamically get a pointer to references, given just the string "references"?

Once I have an instance of the MyBook class like this:

my_book_model = MyBook.objects.get(id=some_id)

I don't know how to get the pointer to my_book_model.references. Once I have that pointer, then I can just pass the values array to the pointer.values(values_array)

CodePudding user response:

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(…).

  • Related