如何将数据添加到ManyToMany字段? [英] How to add data into ManyToMany field?

查看:94
本文介绍了如何将数据添加到ManyToMany字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在任何地方都找不到它,所以您的帮助对我非常有用:)这是该字段:

I can't find it anywhere, so your help will be nice for me :) Here is that field:

categories = models.ManyToManyField(fragmentCategory)

FragmentCategory:

FragmentCategory:

class fragmentCategory(models.Model):

        CATEGORY_CHOICES = (
                        ('val1', 'value1'),
                        ('val2', 'value2'),
                        ('val3', 'value3'),
                        )

        name = models.CharField(max_length=20, choices=CATEGORY_CHOICES)

以下是发送表格:

<input type="checkbox" name="val1" />
<input type="checkbox" name="val2" />
<input type="checkbox" name="val3" />






我尝试过这样的事情:


I tried something like this:

categories = fragmentCategory.objects.get(id=1),

或:

categories = [1,2]


推荐答案

整个Django文档的页面专门为此,并在内容页面中对其进行了索引。

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

如该页面所示,您需要执行以下操作:

As that page states, you need to do:

my_obj.categories.add(fragmentCategory.objects.get(id=1))

my_obj.categories.create(name='val1')

这篇关于如何将数据添加到ManyToMany字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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