How to add data into ManyToMany field?

前端 未结 2 1588
不知归路
不知归路 2020-12-02 10:33

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

categories = models.ManyToManyField(fragmentCategory)

Fr

相关标签:
2条回答
  • 2020-12-02 10:49

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

    0 讨论(0)
  • 2020-12-02 10:52

    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')
    
    0 讨论(0)
提交回复
热议问题