I want to be able to update a many-to-many field on a model, when the name of the field is stored in a variable. This is relatively easy for a normal field (with kwargs in the constructor), or even a foreign key, but not so for a many-to-many field. Here's the situation:
class Book(models.Model):
title = models.CharField(max_length=30)
authors = models.ManyToManyField(Author)
field_name = 'title'
new = Book(**{field_name:'My Book'}) # This sets title to mybook
new.save()
my_authors = Author.objects.filter(name='Ben') # Get some authors
field_name = 'authors'
new.XXXXXX = my_authors # Add them
How to do the XXXXXX bit is what I'm asking! It isn't accepted in the kwargs like other fields, as you need a primary key first and that can't happen until it's been saved. Any ideas? Any help very greatly appreciated! It must be possible - the django admin must do it some how but I can't find where.
*Edit - I'm ideally looking for a solution that doesn't use __getattribute or __setattr - though they do work, they're not ideal. Also, I can't alter the model in any way when doing this, that's somebody else's code. Thanks!
Thanks guys. Ben