在我的网站上,我有一个公共游戏列表供用户玩。我想对此列表进行分页,以便每页只显示20个游戏。同时,我想继续游戏统计数据,以便用户可以知道他们是否玩过游戏,以及他们是否喜欢游戏(因此URL可以改变)。目前它导致我的网站一大堆痛苦。我正在使用内置的Paginator。
我的代码:
def games(request):
thisuser = request.user
games_list = Game.objects.filter(private_game=False).order_by('-pubdate')
paginator = Paginator(games_list, 20)
next = request.path
page = request.GET.get('page')
try:
games = paginator.page(page)
except PageNotAnInteger:
games = paginator.page(1)
except EmptyPage:
games = paginator.page(paginator.num_pages)
args = {'games': games}
args.update(csrf(request))
for game in games:
played = (game, Result.objects.filter(player=thisuser, game=game).exists())
liked = (game, Game.objects.filter(id=game.id, gamelikes=thisuser).exists())
args['games'].append(played, liked)
return render(request, 'games.html', args)
错误是"' Page'对象没有属性'追加'"
游戏模型:
class Game(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
description = models.TextField(null=True, blank=True)
pubdate = models.DateTimeField(default=timezone.now)
createdby = models.ForeignKey(User, related_name='game_creator')
lastedit = models.DateTimeField(default=timezone.now)
private_game = models.BooleanField(default=False)
private = models.ManyToManyField(User, related_name='private_game_players')
item01 = models.CharField(max_length=200, null=True, blank=True)
item01photocount = models.IntegerField(default=0)
item02 = models.CharField(max_length=200, null=True, blank=True)
item02photocount = models.IntegerField(default=0)
item03 = models.CharField(max_length=200, null=True, blank=True)
item03photocount = models.IntegerField(default=0)
item04 = models.CharField(max_length=200, null=True, blank=True)
item04photocount = models.IntegerField(default=0)
value = models.CharField(max_length=200, null=True, blank=True)
endby_date = models.DateField(null=True, blank=True)
game_closed = models.BooleanField(default=False)
location = models.CharField(max_length=200, null=True, blank=True)
gamelikes = models.ManyToManyField(User, related_name='game_likes')
photocount = models.IntegerField(default=0)
答案 0 :(得分:0)
您可以通过将属性直接粘贴到对象上来简化代码。
# ...
for game in games:
game.played = Result.objects.filter(player=thisuser, game=game).exists()
game.liked = Game.objects.filter(id=game.id, gamelikes=thisuser).exists()
ctx = {'games': games}
ctx.update(csrf(request))
return render(request, 'games.html', ctx)
当您遍历模板中的games
对象时,您可以访问属性:
{% for game in games %}
{{ game.played }}, {{ game.liked }}
{% endfor %}
唯一要注意的是确保不要覆盖game
对象上可能包含的属性,例如通过将属性添加到extra_has_played
或extra_has_liked
之类的前缀。