django.db.utils.IntegrityError: UNIQUE constraint failed: store_wishlist.user_id
django.db.utils.IntegrityError: UNIQUE constraint failed: store_wishlist.user_id
我在电子商务网站上工作。我想在我的网站上实现愿望清单功能。而且,如果用户是第一次添加到列表中,它就会工作。第二次报错。有什么问题?有人可以帮帮我吗?
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)
脚本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()
})
}
将 Wishlist.user
更改为 models.ForeignKey
以便您可以为每个用户添加多个,您可以向模型添加唯一约束以仅允许用户使用 [= 添加一次产品17=]
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'),
)
在您看来,您不需要 if
块,您可以使用 get_or_create 仅在不存在的情况下创建一个新条目
Wishlist.objects.get_or_create(user=user, product=product)
要从用户的心愿单中删除产品(无论是否存在),您可以在过滤的查询集上使用 delete()
方法
deleted = Wishlist.objects.filter(user=user, product=product).delete()
if deleted == 0:
# Can do something when nothing was deleted if you like
我在电子商务网站上工作。我想在我的网站上实现愿望清单功能。而且,如果用户是第一次添加到列表中,它就会工作。第二次报错。有什么问题?有人可以帮帮我吗? 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)
脚本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()
})
}
将 Wishlist.user
更改为 models.ForeignKey
以便您可以为每个用户添加多个,您可以向模型添加唯一约束以仅允许用户使用 [= 添加一次产品17=]
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'),
)
在您看来,您不需要 if
块,您可以使用 get_or_create 仅在不存在的情况下创建一个新条目
Wishlist.objects.get_or_create(user=user, product=product)
要从用户的心愿单中删除产品(无论是否存在),您可以在过滤的查询集上使用 delete()
方法
deleted = Wishlist.objects.filter(user=user, product=product).delete()
if deleted == 0:
# Can do something when nothing was deleted if you like