如何将数据添加到ManyToManyField? [英] how to add data into ManyToManyField?

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

问题描述

我不能在任何地方找到它,所以你的帮助对我来说很好:)这是这个领域:

 类别= models.ManyToManyField(fragmentCategory)

FragmentCategory:


$ b $

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


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

以下是要发送的表单:

 < input type =checkboxname =val1/> 
< input type =checkboxname =val2/>
< input type =checkboxname =val3/>






我尝试过这样的东西:

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

或者:

  categories = [1,2] 


解决方案

有一整页的Django文档致力于此,从内容页面进行索引。



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

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

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


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

categories = models.ManyToManyField(fragmentCategory)

FragmentCategory:

class fragmentCategory(models.Model):

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

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

Here is the form to send:

<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),

Or:

categories = [1,2]

解决方案

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))

or

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

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

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