我的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, })
答案 0 :(得分:2)
添加ManyToMany使这个问题变得容易解决:
class Dishes(models.Model):
name = models.CharField(max_length=40, unique=True)
likes = models.ManyToManyField(Likes)
class Likes(models.Model):
dish = models.ForeignKey(Dishes)
user = models.ForeignKey(User)
date_added = models.DateTimeField(auto_now_add=True)
调整您的视图:
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
@login_required
def home(request):
dishes = Dishes.objects.all()
return_list = []
for dish in dishes:
return_list.append((dish, dish.likes_set.filter(user=request.user)))
return render(request, 'dish_list.html', {'dishes': return_list})
您的模板是“切换”的地方:
{% for dish, liked in dishes %}
{{ dish.name }}
{% if liked %}
You already like this dish.
{% else %}
Like this dish now, its yummy!
{% endif %}
{% endfor %}
或者,如果您无法更改模型,请调整以下视图代码:
@login_required
def home(request):
dishes = Dishes.objects.all()
return_list = []
for dish in dishes:
return_list.append((dish,
Likes.objects.filter(user=request.user, dish=dish)))
return render(request, 'dish_list.html', {'dishes': return_list})
我们的想法是,已经为登录的用户标记了返回到模板的对象列表。
login_required
decorator确保仅在用户登录时调用视图。否则,它会将用户重定向到登录页面。
render
shortcut将确保始终从您的观看传递RequestContext
。
答案 1 :(得分:0)
你需要一个新的模型并假设你使用的是django用户模型,你可以这样:
<强> models.py 强>
from django.contrib.auth.models import User
class DishLiked(models.Model):
dish = models.ForeignKey(Dish,
related_name='liked_by'
)
like = models.ForeignKey(Like,
related_name='like_by'
)
user = models.ForeignKey(User,
related_name='liked_dishes'
)
<强> views.py 强>
注意:还要注意他们从request
获取用户的方式:
def home(request):
user = request.user
liked = DishLiked.objects.filter(
user__id=user.id
)
dish_id_list = []
for liked_dish on liked:
dish_id_list.append(liked_dish.dish.pk)
dishes_liked_by_user = Dish.objects.filter(id__in=dish_id_list)