Django将2个模型实例与m2m字段合并,指定中间模型

时间:2018-01-08 09:14:45

标签: python django many-to-many

我使用脚本自动合并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个问题:

  1. 是否有任何内置函数可以区分指定中间模型的m2m字段和m2m字段,而不是? (因为对于正常的m2m字段,这个add()函数看起来效果很好。)
  2. 使用指定的m2m字段,如何优雅地删除/添加模型实例到该关系?
  3. 感谢您的时间!

0 个答案:

没有答案