How to add data into ManyToMany field?

DjangoDjango Models

Django Problem Overview


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]

Django Solutions


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

or

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

Solution 2 - Django

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIProblemFactoryView Question on Stackoverflow
Solution 1 - DjangoDaniel RosemanView Answer on Stackoverflow
Solution 2 - DjangoChrisView Answer on Stackoverflow