# I can't add Many-To-Many relation in Django

**URL:** <https://forum.djangoproject.com/t/i-cant-add-many-to-many-relation-in-django/4938>\
**Category:** Using Django\
**Created:** [October 24, 2020, 9:52am UTC](https://forum.djangoproject.com/t/i-cant-add-many-to-many-relation-in-django/4938 "2020-10-24T09:52:04Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![antpngl92](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/antpngl92/32/1035_2.png) [@antpngl92](https://forum.djangoproject.com/u/antpngl92)\
**Post date:** [October 24, 2020, 9:52am UTC](https://forum.djangoproject.com/t/i-cant-add-many-to-many-relation-in-django/4938/1 "2020-10-24T09:52:04Z")

</div>

Hi guys,

I have 2 models:

models.py:

```auto
class Item(models.Model):
    name = models.CharField(max_length=100)
    price = models.FloatField(max_length=20)
    shelfLife = models.BooleanField()
   
    def __str__ (self):
        return self.name  

    @property
    def shL(self):
        temp = "Doesnt' have shelf life"
        if(self.shelfLife):
            temp = "Does have sehlf life"
        return temp

class Order(models.Model):
    num = models.CharField(max_length=20)
    date = models.DateField()
    items = models.ManyToManyField(Item)
   
    def __str__ (self):
        return self.num 

```

according to this [doc](https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/) I can do:

views.py:

```auto
    elif request.method == "POST":
        list_items = request.POST.getlist('arr[]') # get list of items
        order_num = request.POST.getlist('o_n') # get order num
        order_date = request.POST.getlist('o_d') # get order date 
        
        order = Order(num=order_num[0], date=order_date[0])
        order.save()
        items = Item.objects.filter(name__in=list_items)
        
        order.items.add(*items)

```

I still get a QuerySet `items` as an empty QuerySet.  
I have checked the request variable `list_tems` and it is a list of strings (it’s not empty).  
I tested it by creating an array of Strings

```auto
arr=["Salad", "Chocolate"]

```

and paste it as a filter

```auto
items = Item.objects.filter(name__in=arr)
order.items.add(*items)

```

to the QuerySet and it works - QuerySet object `items` is not empty and it writes the right data to the DB.

```auto
item = Item.objects.filter(name="Salad")

```

the returned QuerySet is not empty, however, if I pass a string variable to the `name` filter it returns an empty QuerySet.

index.html:

```auto
 $(document).on('click','.btn-create-order',function(){              
                $.ajax({
                    method: "GET",
                    contentType: "application/json",
                    url: "{% url 'order-items api' %}", 
                    success: function(data){
                        var index = 1;
                        data.forEach(element => {
                            $('#multyItemSelect').append("<option value='" + index + "' id='" +index+ "'> "+ element['fields'].name+"</option>")
                            index++;
                        });
                    },
                    error: function(jqXHR, textStatus, errorThrown){}
                })        
            })
            $('.order-new-submit').click(function(){
                var order_num = $('#InputNumber').val()
                var order_date = $('#InputDate').val()
                var item_selected = $('#multyItemSelect').val() // number 
                var arr = [] // arr for the item names 
                
                
                var index = 0;
                item_selected.forEach(e => {
                    arr[index] = $('#' + e).html()
                    index++
                });
                console.log(order_date)
                // DEBUGIN
                // arr.forEach(e => {
                // console.log(e)
                // });
                // END DEBUGIN

                $.ajax({
                    method: "POST",
                    url: "{% url 'order-items api' %}",
                    data: {'arr[]': arr,
                            'o_n' : order_num,
                            'o_d' : order_date},
                    success: function(data){
       
                    },
                    error: function(jqXHR, textStatus, errorThrown){}
                })
            })

```

I would appreciate any help!  
Thanks

---

<div class="post-metadata">

**Author:** ![antpngl92](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/antpngl92/32/1035_2.png) [@antpngl92](https://forum.djangoproject.com/u/antpngl92)\
**Post date:** [October 24, 2020, 11:24am UTC](https://forum.djangoproject.com/t/i-cant-add-many-to-many-relation-in-django/4938/2 "2020-10-24T11:24:02Z")

</div>

Issue has been found:

```auto
print(list_items)

```

gives me output:

```auto
[' Salad', ' Beef Stake ', ' Chocolate']

```

There is a leading space character in each `Item.name`

---

<div class="post-metadata">

**Author:** ![jlgimeno](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jlgimeno/32/284_2.png) [@jlgimeno](https://forum.djangoproject.com/u/jlgimeno)\
**Post date:** [October 24, 2020, 7:29pm UTC](https://forum.djangoproject.com/t/i-cant-add-many-to-many-relation-in-django/4938/3 "2020-10-24T19:29:44Z")

</div>

I appreciate you posted the solution. It will help one of us down the road. Thank you!

-Jorge

---

<div class="post-metadata">

**Author:** ![marcorichetta](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/marcorichetta/32/26473_2.png) [@marcorichetta](https://forum.djangoproject.com/u/marcorichetta)\
**Post date:** [October 24, 2020, 11:46pm UTC](https://forum.djangoproject.com/t/i-cant-add-many-to-many-relation-in-django/4938/4 "2020-10-24T23:46:25Z")

</div>

Hi! Glad to hear you already solved it!

Just wanted to ask, why are you using `*items` with an asterisk here?

> [@antpngl92](#):
>
> ```auto
> items = Item.objects.filter(name__in=list_items)    
> order.items.add(*items)
> 
> ```

As I understand `items` cointains a Queryset of `Item` objects, but `*items` unpacks that queryset.

* * *

Reading [this example from the docs](https://docs.djangoproject.com/en/2.2/ref/models/relations/#django.db.models.fields.related.RelatedManager.add) I just learned that in this case it works both with **items** and \ ***items**.

> For many-to-many relationships `add()` accepts either model instances or field values, normally primary keys, as the `*objs` argument.

---

<div class="post-metadata">

**Author:** ![antpngl92](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/antpngl92/32/1035_2.png) [@antpngl92](https://forum.djangoproject.com/u/antpngl92)\
**Post date:** [October 25, 2020, 12:00am UTC](https://forum.djangoproject.com/t/i-cant-add-many-to-many-relation-in-django/4938/5 "2020-10-25T00:00:08Z")

</div>

`item` in `order.items.add(…)` needs to be a model _object_ , or the primary key of that model, but not a queryset. You can however make use of iterable unpacking to pass the items wrapped in the `QuerySet` as individual parameters with the asterisk here.

---

<div class="post-metadata">

**Author:** ![marcorichetta](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/marcorichetta/32/26473_2.png) [@marcorichetta](https://forum.djangoproject.com/u/marcorichetta)\
**Post date:** [October 25, 2020, 8:03pm UTC](https://forum.djangoproject.com/t/i-cant-add-many-to-many-relation-in-django/4938/6 "2020-10-25T20:03:23Z")

</div>

> [@marcorichetta](#):
>
> As I understand `items` cointains a Queryset of `Item` objects, but `*items` unpacks that queryset.

I just wrote that sentence knowing that you can’t pass a queryset to `add()`, but in my head passing the `items` queryset in your case was correct, therefore I didn’t see the need to unpack it. 🤦‍♂️
