问题
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
回答1:
Reading your answer, I think that this is you are looking for:
relation_name = 'authors'
new.__getattribute__(relation_name) = my_authors
With out parametrize relation name django n:m doc say:
new.authors = my_authors
回答2:
This assumes that the authors are not being created, but being added to the M2M field for the book.
my_authors = Author.objects.filter(name='Ben') # Get some authors
# This will append all authors from my_authors to the M2M field.
for a in my_authors:
new.authors.add(a)
Is this what you are looking for?
来源:https://stackoverflow.com/questions/8360867/update-many-to-many-field-in-django-with-field-name-in-variable