How to add data to the ManyToMany field?

I can’t find it anywhere, so your help will be pleasant for me :) Here is this 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 submit:

 <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] 
+58
django django-models
Jul 25 '09 at 16:02
source share
2 answers

Here's an entire page of Django documentation well indexed on the content page.

As indicated on this page, you need to do:

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

or

 my_obj.categories.create(name='val1') 
+106
Jul 25 '09 at 17:31
source share

In case someone else ends up here trying to set up the Many2Many administrative form to save, you cannot call self.instance.my_m2m.add(obj) in the override of ModelForm.save , since ModelForm.save later fills in 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 

(You can convert an incoming QuerySet to a list β€” either ManyToManyField does ManyToManyField .)

0
Jun 08 '19 at 20:11
source share



All Articles