此add_to_wishlist返回两条消息,最终get_or_create这样。但是我想如果一个项目第一次添加它显示为“已添加”,而下一次“已添加”,但是当我单击该按钮时它都返回。我如何检查或查询返回我的信息,它添加了firstime。
我使用了get_or_create方法。据我所知,当不存在任何项目时,它将创建一个项目,如果已经存在,它将获取或覆盖该项目。我在add_to_cart中尝试过,效果很好。
这是模型
class Wishlist(models.Model):
user =
models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
wished_item = models.ForeignKey(Item,on_delete=models.CASCADE)
slug = models.CharField(max_length=30,null=True,blank=True)
added_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.wished_item.title
@login_required
def add_to_wishlist(request,slug):
item = get_object_or_404(Item,slug=slug)
wished_item,created =
Wishlist.objects.get_or_create(wished_item=item,
slug = item.slug,
user = request.user,
)
messages.info(request,'The item was added to your wishlist')
wish_list_qs = Wishlist.objects.filter(user = request.user,
slug=item.slug)
if wish_list_qs.exists():
messages.info(request,'The item was already in your wishlist')
return redirect('core:product_detail',slug=slug)
它同时显示了两条消息....但是我想要根据操作添加一个消息还是第一次添加还是再次添加
该商品已添加到您的愿望清单
该商品已经在您的愿望清单中
答案 0 :(得分:1)
应用wish_list_qs.exists()
方法后检查get_or_create
将始终返回True
值。
另外,当您将get_or_create
用于wished_item
时,这样做是徒劳的
wish_list_qs = Wishlist.objects.filter(user = request.user, slug=item.slug)
,然后在其上应用exists()
方法。
上面的语句将返回您创建的对象,即wished_item
。
您需要在代码中进行的更改是
def add_to_wishlist(request,slug):
item = get_object_or_404(Item,slug=slug)
wished_item,created =
Wishlist.objects.get_or_create(wished_item=item,
slug = item.slug,
user = request.user,
) # Creating or extracting the wished item
if created:
# if new wished_item created
messages.info(request,'The item was added to your wishlist')
else:
# if wished_item existed previously
messages.info(request,'The item was already in your wishlist')
return redirect('core:product_detail',slug=slug)