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

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

问题描述

我在任何地方都找不到它,所以你的帮助对我很有帮助:) 这是那个字段:

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

categories = models.ManyToManyField(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天全站免登陆