gpt4 book ai didi

django - 'QuerySet' 对象没有属性

转载 作者:行者123 更新时间:2023-12-03 21:27:16 25 4
gpt4 key购买 nike

请问我为什么在我的模板中显示“fav”时收到此错误消息

QuerySet object has no attribute game_id

我试图更换 game_id来自 game , id_game但没什么……

查看.py
from django.contrib import messages
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render
from start.models import Games, FavoriteGames
import urllib, json

def view_recap(request):
if request.user.is_authenticated():
username = request.user.username
id_user = request.user.id
fav = FavoriteGames.objects.filter(user_id=id_user).game_id
return render(request, 'recap.html', locals())
else:
from start.views import view_logoff
from start.views import view_logon
messages.add_message(request, messages.INFO, 'Vous devez être connecté pour accéder à cette page.')
return redirect(view_logon)

模型.py
from django.db import models
from django.conf import settings

# Create your models here.
class Games(models.Model):
guid = models.CharField(max_length=100, unique=True, null=False, verbose_name="GUID")
title = models.CharField(max_length=100, null=False, verbose_name="Titre")
logo = models.CharField(max_length=100, null=True, blank=True, verbose_name="Logo")
date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création")
update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification")
def __str__(self):
return self.title

class FavoriteGames(models.Model):
game = models.ForeignKey('Games')
user = models.ForeignKey(settings.AUTH_USER_MODEL)

最佳答案

当您遍历查询集时,您可以访问 game_id对于每个实例。您无法在查询集上访问它。

您可以遍历 View 中的查询集,

favs = FavoriteGames.objects.filter(user_id=id_user)

for fav in favs:
game_id = game_id

或在模板中:
{% for fav in favs %}
{{ fav.game_id }}
{% endfor %}

如果您只需要 game_ids从查询集中,您可以使用 values_list :
game_ids = FavoriteGames.objects.filter(user_id=id_user).values_list('game_id', flat=True)

关于django - 'QuerySet' 对象没有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44284850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com