Django多对多字段导致错误

Rya*_*axe 4 python django many-to-many python-2.7

我创建了一个将对象添加到模型的函数.它看起来像这样:

def add_objects(self,obj_name_list):
    for obj in obj_name_list:
        o = Obj.objects.create(name=obj)
        self.objs.add(o)
        self.save(update_fields['objs'])
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,我收到以下错误:

ValueError:此模型中不存在以下字段,或者是m2m字段:objs

错误来自save()通话,但我不明白为什么......在你的回答中请详细解释.谢谢!

这是追溯

.../models.pyc in add_objects(self, obj_name_list)
    125                                 o = Obj.objects.create(name=obj) #create the tag
    126                                 self.objs.add(o) #add the new tag to the foreign key
--> 127                                 self.save(update_fields=['objs'])
    128                 except TypeError:
    129                         raise TypeError("You can only add objects as a string or list")

.../models.pyc in save(self, *args, **kwargs)
     95                 if not self.pk:
     96                         is_created = True
---> 97                 super(Model, self).save(*args, **kwargs)
     98                 if is_created:
     99                         signals.model_created.send(sender=self.__class__) #send signal if just created

/Library/Python/2.7/site-packages/Django-1.6-py2.7.egg/django/db/models/base.pyc in save(self, force_insert, force_update, using, update_fields)
    523                 raise ValueError("The following fields do not exist in this "
    524                                  "model or are m2m fields: %s"
--> 525                                  % ', '.join(non_model_fields))
    526
    527         # If saving to the same database, and this model is deferred, then
Run Code Online (Sandbox Code Playgroud)

Dan*_*man 9

跟踪显示,这不是您运行的代码.有问题的代码是这样的:

self.save(update_fields=['objs'])
Run Code Online (Sandbox Code Playgroud)

这确实会导致问题,因为objs它不是该模型上的实际字段:它是链接表中的一列.

实际上,如果您还没有修改任何其他字段,则根本不需要调用save:在m2m字段上调用add已经修改了数据库.