我使用脚本自动合并2个Django模型实例(因此它可以用于我系统中的任何类型的模型)。但是当处理指定中间模型的m2m字段的部分时存在问题(在定义此字段时使用through
参数),我得到错误:AttributeError: Cannot use remove() on a ManyToManyField which specifies an intermediary model. Use <MyModel>'s Manager instead
# Migrate all many to many references from alias object to primary object.
for related_many_object in get_all_related_many_to_many_objects(alias_object):
alias_varname = related_many_object.get_accessor_name()
obj_varname = related_many_object.field.name
if alias_varname is not None:
# standard case
related_many_objects = getattr(alias_object, alias_varname).all()
else:
# special case, symmetrical relation, no reverse accessor
related_many_objects = getattr(alias_object, obj_varname).all()
for obj in related_many_objects.all():
getattr(obj, obj_varname).add(primary_object) #This line raises the AttributeError
getattr(obj, obj_varname).remove(alias_object)
这是返回需要合并的对象的所有m2m字段的函数:
def get_all_related_many_to_many_objects(obj):
return [
f for f in obj._meta.get_fields(include_hidden=True)
if f.many_to_many and f.auto_created
]
我对这个案子有2个问题:
感谢您的时间!