Create multiple instances with given fields
I have these models
class Guest(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
surname = models.CharField(max_length=100, blank=True, null=True)
phone_number = models.CharField(max_length=50, blank=True, null=True)
adress = models.CharField(max_length=200, blank=True, null=True)
table = models.ForeignKey(Table, on_delete=models.CASCADE, blank=True, null=True)
class Dish(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
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)
And I get this data from postman
{
"guests":{
"23": [1, 2, 3],
"24": [1, 2],
"25": [1]
}
}
So here 23-25 are guest ids and 1-3 are dish id.
This is the view (I also get table_id from posman but that's irrelevant for question)
class CreateOrderView(APIView):
def post(self, request):
table_id = request.data.get('table_id')
table = Table.objects.get(id=table_id)
number_of_guests = int(request.data.get('number_of_guests'))
guest_orders = []
guests = []
for i in range(number_of_guests):
guest = Guest()
guest.table = table
guest.first_name = str(i)
guests.append(guest)
Guest.objects.bulk_create(guests, number_of_guests)
guests = request.data.get('guests')
for key, value in guests.items():
guest = find_guests(key)
print(guest)
# print(value)
dish = find_dish(value)
print(dish)
GuestOrder.objects.create(guest=guest, table=table)
guest_orders = GuestOrder.objects.filter(table=table)
for guestorder in guest_orders:
guestorder.dish.set(dish)
return Response("5")
these are the helper functions used in the view.
def find_guests(id):
found_guest = Guest.objects.get(id=id)
return found_guest
def find_dish(list):
for y in list:
found_dishes = []
found_dish = Dish.objects.get(id=y)
found_dishes.append(found_dish)
return found_dishes
I've created the order for each guest and what I'm failing at is setting given dishes for each GuestOrder After calling this api it creates e GuestOrders and all 3 of them have 1-3 dishes and I need first GuestOrder to have dish with id=1, second one id=1 and id=2 and the third all dishes 1-3.