django 无法在指定中间模型的 ManyToManyField 上设置值。使用管理器代替

发布于 2024-09-06 13:07:51 字数 1611 浏览 3 评论 0原文

我正在努力在同一表格上保存两个表 - 具有 M2M 关系。 我没有成功,我的错误仍然存​​在,如下所示:无法在指定中间模型的 ManyToManyField 上设置值。使用会员经理代替 其中 Membership 是我的“直通表”。

我的代码:

def save_classroom(request):
   classroom_instance = Classroom()
   if request.method == 'POST':
        form = ClassroomForm(request.POST, request.FILES, user = request.user) 
        if form.is_valid():
           new_obj = form.save(commit=False)
           new_obj.user = request.user 
           new_obj.save()
           membership = Membership(member = request.user,classroom=new_obj)
           membership.save() 
           form.save_m2m()
           return HttpResponseRedirect('.')    
   else:
           form = ClassroomForm(user = request.user)     
   return render_to_response('classroom/classroom_form.html', {
           'form': form,

           }, 
          context_instance=RequestContext(request))  

我的模型:

class Classroom(models.Model):
     user = models.ForeignKey(User, related_name = 'classroom_creator')
     classname = models.CharField(max_length=140, unique = True)
     date = models.DateTimeField(auto_now=True)
     open_class = models.BooleanField(default=True)
     members = models.ManyToManyField(User,related_name="list of invited members", through = 'Membership')

class Membership(models.Model): 
      accept = models.BooleanField(default=False)
      date = models.DateTimeField(auto_now = True) 
      classroom = models.ForeignKey(Classroom, related_name = 'classroom_membership')
      member = models.ForeignKey(User, related_name = 'user_membership')

我错在哪里?

i am working on saving on the same form two tables - having a m2m relation.
I don't succeed, my error persists with something like: Cannot set values on a ManyToManyField which specifies an intermediary model. Use Membership's Manager instead
where Membership is my 'through table'.

my code :

def save_classroom(request):
   classroom_instance = Classroom()
   if request.method == 'POST':
        form = ClassroomForm(request.POST, request.FILES, user = request.user) 
        if form.is_valid():
           new_obj = form.save(commit=False)
           new_obj.user = request.user 
           new_obj.save()
           membership = Membership(member = request.user,classroom=new_obj)
           membership.save() 
           form.save_m2m()
           return HttpResponseRedirect('.')    
   else:
           form = ClassroomForm(user = request.user)     
   return render_to_response('classroom/classroom_form.html', {
           'form': form,

           }, 
          context_instance=RequestContext(request))  

my models:

class Classroom(models.Model):
     user = models.ForeignKey(User, related_name = 'classroom_creator')
     classname = models.CharField(max_length=140, unique = True)
     date = models.DateTimeField(auto_now=True)
     open_class = models.BooleanField(default=True)
     members = models.ManyToManyField(User,related_name="list of invited members", through = 'Membership')

class Membership(models.Model): 
      accept = models.BooleanField(default=False)
      date = models.DateTimeField(auto_now = True) 
      classroom = models.ForeignKey(Classroom, related_name = 'classroom_membership')
      member = models.ForeignKey(User, related_name = 'user_membership')

where am i wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

め可乐爱微笑 2024-09-13 13:07:51

如果允许修改 class Membership,添加 auto_created = True 可能会解决您的问题,

class Membership(models.Model): 
    class Meta:
        auto_created = True

在 Django 1.7 中,错误消息更改为“无法在 ManyToManyField 上设置值,指定一个中介模型”。解决方案是一样的。

注意:这将完全删除您的中间模型及其所有附加字段。

If you are allowed to modify class Membership, adding auto_created = True might solve your problem,

class Membership(models.Model): 
    class Meta:
        auto_created = True

In Django 1.7, the error message is changed to "Cannot set values on a ManyToManyField which specifies an intermediary model". The solution is the same.

NOTE: This will remove your intermediate model entirely, and all the additional fields with it.

信愁 2024-09-13 13:07:51

如上所示:

http://docs.djangoproject.com/ en/dev/topics/db/models/#intermediary-manytomany

与普通的多对多字段不同,您不能使用添加、创建或赋值(即,beatles.members = [...])来创建关系

我猜您的代码会在“form.save_m2m( )”,这是不必要的,因为您已经手动创建了成员资格。

As seen on:

http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany

Unlike normal many-to-many fields, you can't use add, create, or assignment (i.e., beatles.members = [...]) to create relationships

I guess your code trips up on the line "form.save_m2m()", which is unnecessary since you already manually create a membership.

帝王念 2024-09-13 13:07:51

我在另一个问题上有类似的错误消息。我将其发布在这里以防对其他人有帮助。

我在现有模型上添加了新的 ManyToManyField。该模型用于使用 exclude 字段构建的 ModelForm 中。

我通过在排除的字段中添加新字段解决了该问题。

I had a similar error message on a different problem. I post it here just in case it helps others.

I've added a new ManyToManyField on an existing model. This model was used in a ModelForm built with an exclude field.

I fixed the problem by add the new field in the excluded ones.

驱逐舰岛风号 2024-09-13 13:07:51

Django 2.2 版本 开始,您还可以指定 through_defaults 在字段上以便使用添加、创建和分配:

RelatedManager.add()、create()remove()set()get_or_create(),
update_or_create() 方法现在允许在多对多上使用
与中间模型的关系。新的 through_defaults
参数用于指定新中间模型的值
实例。

在你的情况下,因为所有字段都已经有默认值,所以它可能只在 2.2 中工作。

As of the Django 2.2 release you can also specify a through_defaults on the field in order to use add, create and assignment:

The RelatedManager.add(), create(), remove(), set(), get_or_create(),
and update_or_create() methods are now allowed on many-to-many
relationships with intermediate models. The new through_defaults
argument is used to specify values for new intermediate model
instance(s).

In your case since all the fields already have defaults it might just work in 2.2.

微暖i 2024-09-13 13:07:51

https://docs.djangoproject.com/en/2.1/ 中指定的topic/db/models/

“与普通的多对多字段不同,您不能使用 add()、create() 或 set() 来创建关系”

这意味着对于 django 2.1 版本,这些方法是不可能的。但 django 2.2 文档的同一页 https://docs.djangoproject.com /en/2.2/topics/db/models/ 告诉我们:

“您还可以使用 add()、create() 或 set() 来创建关系,只要为任何必填字段指定 through_defaults 即可”

因此,只需将 django 更新到 2.2 或更新版本即可使用上述方法,并在创建对象时将参数“through_defaults”作为 python 字典,其中键作为额外字段名称,值作为默认值。

As specified in https://docs.djangoproject.com/en/2.1/topics/db/models/

"Unlike normal many-to-many fields, you can’t use add(), create(), or set() to create relationships"

This means for django version 2.1 ,these methods are impossible. But the same page of django 2.2 documentation https://docs.djangoproject.com/en/2.2/topics/db/models/ tells that:

"You can also use add(), create(), or set() to create relationships, as long as you specify through_defaults for any required fields"

So just update the django to 2.2 or newer versions to use the above methods and while creating objects give the argument 'through_defaults' as a python dictionary with keys as your extra field names and values as their default values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文