0

How can I use a jquery ajax call to POST a new record for a model that contains a ManyToMany field?

My model:

class Foo(models.Model):
  bar = models.ManyToManyField(Qux, blank=True)
  baz = CharField(max_length=15)

class Qux(models.Model):
  id = models.AutoField(primary_key=True)

My js:

values = {
    bar: ???,
    baz: 'test'
}

$.ajax({
                url: '/api/foo/',
                type: 'PUT',
                data: values,
                success: function(e){
                    console.log('success');
                },
                error: function(){
                    console.log('error')
                }
            });
smilebomb
  • 5,123
  • 8
  • 49
  • 81

1 Answers1

0

The simplest thing to do would be to pass a list of IDs corresponding to the Qux objects with which you want to form a relationship. You can then use those IDs in an add method in your view.

Here's a good SO post on passing a list of IDs via ajax: How to pass a list of id's in a AJAX request to the Server in MVC

Community
  • 1
  • 1
souldeux
  • 3,615
  • 3
  • 23
  • 35