如何将数据添加到 ManyTomany 字段?

我到处都找不到,所以你的帮助对我很有帮助:)这就是那个领域:

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" />

我试过这样的方法:

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

或者:

categories = [1,2]
149446 次浏览

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

In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)