django 将字典中的值添加到多对多字段

wpcxdonn  于 2022-12-20  发布在  Go
关注(0)|答案(2)|浏览(130)
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)

我有一个返回3个GuestOrder示例的查询集。

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

我有一本字典,里面的值是dish的示例。

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

如何将这些值中的每一个设置为一个客户端示例?
这是我试过的(字典的名字是客人)

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

这仅将[3]设置为菜
更新

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

打印的结果如下

[3]
[3]
[3]

我不明白为什么我需要帮助。

xlpyo6sf

xlpyo6sf1#

试试这个

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/

q8l4jmvw

q8l4jmvw2#

所以我将dict值附加到一个新列表中,并迭代查询集和列表。

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

相关问题