我的Django模型Dishes and Likes中有下表。在我的主页上,我显示了数据库中所有菜肴的列表,每道菜上都有一个赞按钮。对于用户喜欢的菜肴,我想表明他们已经喜欢它,以便他们可以不喜欢它,反之亦然。在过去的几天里,我一直在尝试不同的方法,但似乎无法解决任何问题。这是我最近一次失败尝试的代码。
#dishes table
class Dishes(models.Model):
name = models.CharField(max_length=40, unique=True)
def liked(dish, user):
try:
user_upvoted = Likes.objects.get(dish=dish, user=user)
except:
user_upvoted = None
if user_upvoted:
return True
else:
return False
#upvotes
class Likes(models.Model):
dish = models.ForeignKey(Dishes)
user = models.ForeignKey(User)
date_added = models.DateTimeField(auto_now_add=True)
def home(request):
this_user = auth.models.User.objects.get(id=1)
dishes = models.Dishes.objects.all()
for dish in dishes:
models.Dishes.voted(dish, this_user)
`enter code here`return render_to_response('frontend/home.html', { 'dishes': dishes, })