Add values from a dictionary to a ManytoMany field

class GuestOrder(models.Model):
    comment = models.CharField(max_length=400, blank=True, null=True)
    guest = models.ForeignKey(Guest, on_delete=models.SET_NULL, null=True)
    dish = models.ManyToManyField(Dish)
    ingredient = models.ManyToManyField(Ingredient)
    table = models.ForeignKey(Table, on_delete=models.CASCADE, blank=True, null=True)

I have a queryset that returns 3 instances of GuestOrder.

guest_orders = GuestOrder.objects.filter(table=table)
<QuerySet [<GuestOrder: GuestOrder object (567)>, <GuestOrder: GuestOrder object (568)>, <GuestOrder: GuestOrder object (569)>]>

and I have a dictionary where values are dish instances.

{
    "guests":{
        "23": [1, 2],
        "24": [2],
        "25": [3]
    }
}

How to set each of this values to a guestorder instance?

This is what I tried (the name of the dictionary is guests)

for guestorder in guest_orders:
    for key, value in guests.items():
        guestorder.dish.set(value)

This only sets [3] as the dish

try this

for guestorder in guest_orders:
    for key, value in guests.items():
        guestorder.dish.add(value)

// or 


for guestorder in guest_orders:
   guest_list = []
   for key, value in guests.items():
       guest_list.append(value)
   guestorder.dish.set(guest_list)

https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/

So I appended the dict values to a new list and iterated over the queryset and the list.

    for value in guests.values():
        dishes.append(value)
    for f, b in zip(guest_orders, dishes):
        f.dish.set(b)
Back to Top