I have a model like this:
class Book(models.Model):
authors = models.ManyToManyField(User) # User is a separate model
readers = models.ManyToManyField(User)
# ... rest of code
I’m trying to create a function outside my views which takes three inputs: a Book, a string and a User. The User is added to the Book’s ManyRelatedManager whose corresponding field name matches the string.
For example, if the function were called foo:
def foo(book, field_name, user):
f = #... this is where I need help, should be a ManyRelatedManager that belongs to 'book'
f.add(user)
book.save()
Calling foo(Book.objects.get(id=1), 'authors', User.objects.get(id=1)) would result in the User with id 1 being added to the field ‘authors’ in the Book with id 1. Similarly, calling foo(Book.objects.get(id=1), 'readers', User.objects.get(id=1)) would result in the User with id 1 being added to the field ‘readers’ in the Book with id 1.
I tried using Book._meta.get_field() but this returned the ManyToManyField itself, not a ManyRelatedManager. Is there some sort of built-in way to get the ManyRelatedManager whose field name matches a string?
Sorry if that description is confusing, my problem is hard to put into words. If anyone can understand my problem, your help is appreciated. Thanks!
getattr()can get an attribute from an object from a string passed to it.