使用变量中的字段名称更新Django中的多对多字段 [英] Update many-to-many field in django with field name in variable

查看:192
本文介绍了使用变量中的字段名称更新Django中的多对多字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当字段名称存储在变量中时,我希望能够更新模型上的多对多字段.对于普通字段(在构造函数中带有kwargs),甚至是外键,这都相对容易,但对于多对多字段则不那么容易.情况如下:

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

我要问的是如何做XXXXXX位!像其他字段一样,它在kwargs中不被接受,因为您首先需要一个主键,并且在保存之前是不可能的.有任何想法吗?任何帮助非常感谢!一定有可能-django管理员必须以某种方式做到这一点,但我找不到哪里.

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.

* 编辑-我理想的情况是寻找一种不使用__getattribute或__setattr的解决方案-尽管它们确实起作用,但它们并不理想.另外,在执行此操作时,我无法以任何方式更改模型,那是别人的代码.谢谢!

*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!

谢谢大家. 本

推荐答案

阅读您的答案,我认为这是您在寻找的东西:

Reading your answer, I think that this is you are looking for:

relation_name = 'authors'
new.__getattribute__(relation_name) = my_authors

没有参数关系名称 django n :m doc 说:

new.authors = my_authors

这篇关于使用变量中的字段名称更新Django中的多对多字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆