Home > Mobile >  django.db.utils.IntegrityError: UNIQUE constraint failed: store_wishlist.user_id
django.db.utils.IntegrityError: UNIQUE constraint failed: store_wishlist.user_id

Time:02-24

I am working on ecommerce website. I wanted to implement wishlist function on my website. And, it is working if its the first time for user that is adding to the list. In the second time giving an error. What's the problem? Can someone please help me? views.py

def addWishlistView(request):
    data = json.loads(request.body)
    productId = data['productId']
    action = data['action']
    print('Action:', action)
    print('Product:', productId)
    user = request.user
    product = Product.objects.get(id=productId)

    if (Wishlist.objects.filter(user=user) and Wishlist.objects.filter(product=product)).exists():
        print("Item is exists")
    else:
        Wishlist.objects.create(user=user,product=product)

    return JsonResponse('Item was added', safe=False)

models.py

class Wishlist(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, verbose_name="Название товара")
    user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True)

script js

for (i = 0; i < wishlist.length; i  ) {
    wishlist[i].addEventListener('click', function(){
        var productId = this.dataset.product
        var action = this.dataset.action

        
        
        if (user == 'AnonymousUser'){
            Console.log("Not logged in");
        }else{
            addToWishlist(productId, action)
        }
    })
}

function addToWishlist(productId, action){
    console.log('User is authenticated, sending data...')

        var url = '/add_wishlist/'

        fetch(url, {
            method:'POST',
            headers:{
                'Content-Type':'application/json',
                'X-CSRFToken':csrftoken,
            }, 
            body:JSON.stringify({'productId':productId, 'action':action})
        })
        
        .then((data) => {
            location.reload()
        })
}

CodePudding user response:

Change Wishlist.user to a models.ForeignKey so that you can add multiple per user, you can add a unique constraint to the model to only allow a user to add a product one time using Meta.unique_together

class Wishlist(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, verbose_name="Название товара")
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        unique_together = (
            ('user', 'product'),
        )

In your view you don't need your if block, you can use get_or_create to only create a new entry if one doesn't already exist

    Wishlist.objects.get_or_create(user=user, product=product)

To delete a product from a user's wishlist if it exists or not you can use the delete() method on a filtered queryset

    deleted = Wishlist.objects.filter(user=user, product=product).delete()
    if deleted == 0:
        # Can do something when nothing was deleted if you like
  • Related