简体   繁体   中英

How to check if data exists or not in Django rest framework

I have a CartModel, CartItem model. I trying to do when I create a cart and when the cart is get created and again I add the same data as I enter in pervious it create another cart. I trying to do that if the cart exists in the CartItem table it has to show the response "Cart already exists". But it is creating another cart. I search a lot and use the code but it will not run. If somebody is capable of giving an answer the please help me.

views.py *

class CartTestViewSet(viewsets.ModelViewSet):
    serializer_class = CartItemSerializer
    permission_classes = (IsAuthenticated,)
    
    def get_queryset(self):
        user = self.request.user
        if user.is_authenticated:
            if user is not None:
                if user.is_active and user.is_superuser or user.is_Customer:
                    return CartItem.objects.all()
                raise PermissionDenied()
            raise PermissionDenied()
        raise PermissionDenied()

    def post(self, request):       
        cart = Cart.objects.filter(user=request.user, cart=request.data, service=request.data, defects=request.data)
        if cart.exists():   
            print('cart already exists')
        else:
            print('cart is created')

serializers.py

from rest_framework import serializers
from .models import CartItem, CartModel
from rest_framework.response import Response

class CartItemSerializer(serializers.ModelSerializer):
    def get_total(self, obj):
        return obj.get_total
    get_total = serializers.IntegerField(read_only=True, required=False)
    # id = serializers.IntegerField(read_only=False)
    class Meta:
        model = CartItem
        fields = "__all__"
        extra_fields = ['get_total']
        read_only = ['get_total']

class CartModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = CartModel
        fields = "__all__"

models.py

from django.db import models
from accounts.models import User, SubCategory
from category.models import Defects
from django.utils import timezone
# Create your models here.

class CartModel(models.Model):
    user = models.ForeignKey('accounts.User', on_delete=models.CASCADE)
    status_choice = [
        ('1', 'open'),
        ('2', 'closed')
    ]
    status = models.CharField(max_length=2, choices=status_choice, default=1)
    
    def __str__(self):
        return self.user.username
    
class CartItem(models.Model):
    cart = models.ForeignKey('CartModel', on_delete=models.CASCADE)
    user = models.ForeignKey('accounts.User', on_delete=models.CASCADE)
    service = models.ForeignKey('accounts.SubCategory', on_delete=models.CASCADE)
    defects = models.ForeignKey('category.Defects', on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)
    price = models.IntegerField()
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now_add=True)


    def __str__(self):
        total = int(self.quantity) * int(self.price)
        return str(total)

    
    def get_total(self):
        total = int(self.quantity )* int(self.price)
        return total

You can use unique=True in your CartItem model. If you try to save a duplicate value with this, django will raise an error.

cart = models.ForeignKey('CartModel', on_delete=models.CASCADE, unique=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM