使用变量中的字段名称更新 django 中的多对多字段
当字段名称存储在变量中时,我希望能够更新模型上的多对多字段。这对于普通字段(构造函数中带有 kwargs)甚至外键来说相对容易,但对于多对多字段则不然。情况是这样的:
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
我要问的是如何做 XXXXXX 位!它不像其他字段一样在 kwargs 中被接受,因为您首先需要一个主键,并且在保存它之前不会发生这种情况。有什么想法吗?非常感谢任何帮助!这一定是可能的 - django 管理员必须以某种方式做到这一点,但我找不到在哪里。
*编辑 - 我理想地寻找一个不使用 __getattribute 或 __setattr 的解决方案 - 尽管它们确实有效,但并不理想。另外,在执行此操作时我无法以任何方式更改模型,那是其他人的代码。谢谢!
谢谢你们。 本
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
阅读您的答案,我认为这就是您正在寻找的:
没有参数化关系名称 django n:m doc 说:
Reading your answer, I think that this is you are looking for:
With out parametrize relation name django n:m doc say:
这假设作者不是被创建的,而是被添加到书籍的 M2M 字段中的。
这是您要找的吗?
This assumes that the authors are not being created, but being added to the M2M field for the book.
Is this what you are looking for?