1

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)
2
  • show dummy request.data and show you serializer Commented May 16, 2020 at 2:23
  • ok added to the edit, not sure how to show request.data other than what i posted hope it helps Commented May 16, 2020 at 3:02

2 Answers 2

1

You can Add cart to serializer like this.

class CartItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = CartItems
        fields = ('recipe','restaurant', 'quantity', 'delivery_date','cart')

Then Modify your function like this.

def addtocart(request):
    customer_id = request.user.id
    cart = Cart.objects.filter(customer_id=customer_id, placed=False).first()
    if not cart:
        cart = Cart.objects.create(customer_id=customer_id, placed=False)

    data = request.data
    data['cart'] = cart
    serializer = CartItemSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.cleaned_data, status=status.HTTP_201_CREATED)

    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Now your questions,

serializer = CartItemSerializer(data=request.data)

Returns a CartItemSerializer instance.

model_instance = serializer.save() 

This would return CartItems model instance.

Sign up to request clarification or add additional context in comments.

Comments

0

try this

@csrf_exempt
@api_view(['POST'])
def add_to_cart(request):
    customer_id = request.user.id
    cart_qs = Cart.objects.filter(customer_id=customer_id, placed=False)
    serializer = CartItemSerializer(data=request.data)
    if cart_qs.exists():
        cart = Cart.objects.get(customer_id=customer_id, placed=False)
    else:
        cart = Cart.objects.create(subtotal=0, placed=False, order_total=0, customer=request.user)

    if serializer.is_valid():
        serializer.save(cart=cart)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

1 Comment

this worked great, before i saw this i came up with another method of doing this using the _set method from django, i show this in EDIT2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.