I have a CartItem object that I am passing from Angular to Django. I am using DRF to serialize the object. My issue is the CartItem has a Foreignkey relationship to a Cart. If a cart does not exist I am creating the cart at that time. But then I want to add that Cart to the CartItem before I save it, I think I am close but cant figure it out..
views.py
@csrf_exempt
@api_view(['POST'])
def addtocart(request):
serializer = CartItemSerializer(data=request.data)
customer_id = request.user.id
cart_qs = Cart.objects.filter(customer_id=customer_id, placed=False)
if serializer.is_valid():
if cart_qs.exists():
existing_cart = cart_qs[0]
new_cartitem = CartItems.objects.create(serializer, cart = existing_cart)
new_cartitem.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
new_cart = Cart.objects.create(subtotal=0, placed=False, order_total=0, customer=request.user)
new_cart.save()
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
model.py
class Cart(models.Model):
placed = models.BooleanField(default=False)
customer = models.ForeignKey(CustomUser, related_name='customuser', on_delete=models.CASCADE)
class CartItems(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
It is this line i need help on: new_cartitem = CartItems.objects.create(serializer, cart = existing_cart)
Also as a side thing, is this line serializer = CartItemSerializer(data=request.data) creating a CartItem object named serializer??
EDIT:
You can also create the relationship from the parent model (Cart in my case) by using the _set attribute
class CartItemSerializer(serializers.ModelSerializer):
class Meta:
model = CartItems
fields = ('recipe','restaurant', 'quantity', 'delivery_date')
data = {dict: 5} {'restaurant': '3', 'recipe': 70, 'quantity': 3, 'customer': 39, 'delivery_date': '2020-05-01'}
'restaurant' = {str} '3'
'recipe' = {int} 70
'quantity' = {int} 3
'customer' = {int} 39
'delivery_date' = {str} '2020-05-01'
__len__ = {int} 5
if serializer.is_valid():
if cart_qs.exists():
existing_cart = cart_qs[0]
new_cart_item = serializer.save()
existing_cart.cartitems_set.add(new_cart_item)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
new_cart = Cart.objects.create(subtotal=0, placed=False, order_total=0, customer=request.user)
new_cart.save()
serializer(cart_id = new_cart.id)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)