Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add data into ManyToMany field?

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] 
like image 890
IProblemFactory Avatar asked Jul 25 '09 16:07

IProblemFactory


People also ask

How do you use many-to-many fields?

When you add a many to many field to a model a separate table is created in the database that stores the links between two models. If you don't need to store any extra information in this third table then you don't have to define a model for it.

What's an example of a many-to-many relationship that would work well with Django's ManyToManyField?

A good example of a many-to-many relationship is the relationship between a sandwich and a sauce. I like a chicken teriyaki sandwich but only if it contains barbeque sauce as well as mayonnaise sauce. So the same sandwich can have multiple sauces.

How do I create a many-to-many relationship in Django?

To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.


1 Answers

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') 
like image 72
Daniel Roseman Avatar answered Sep 19 '22 12:09

Daniel Roseman