我正在尝试查询当前登录用户可以查看他们创建的团队的信息。因此,我正在尝试打印User User的列表,其中UserID =当前用户的ID。我知道我需要使用'所有者'我为团队创建的领域,虽然我不知道在哪里/做什么。
以下是我的观点:
def teamsview(request):
query = UserTeams.objects.filter(userID=request.user)
return render(request, 'teammanager/teams.html', {
"teams": query})
我的团队和用户团队模型:
class Team(models.Model):
name = models.CharField(max_length=100)
venue = models.CharField(max_length=100)
countryID = models.ForeignKey(Countries, on_delete=models.CASCADE)
owner = models.ForeignKey(User)
def __str__(self):
return self.name
class UserTeams(models.Model):
userID = models.ForeignKey(User,on_delete=models.CASCADE)
teamID = models.ForeignKey(Team,on_delete=models.CASCADE)
我的HTML:
{%for team in userteams%}
<h3><a href='/teams/{{userteam.id}}'>{{team.name}}</a></h3>
{%endfor%}
答案 0 :(得分:1)
您确定需要UserTeams
型号吗?您的Team
模型已经拥有User
模型的外键:
class Team(models.Model):
...
owner = models.ForeignKey(User)
因此,在您的视图中,您可以执行以下操作:
from django.contrib.auth.decorators import login_required
@login_required
def teamsview(request):
query = Teams.objects.filter(owner=request.user)
return render(request, 'teammanager/teams.html', {
"teams": query})
login_required
装饰器确保只有已登录的用户才能访问该视图。
然后在您的模板中,循环浏览teams
,以匹配您视图中的{"teams": query}
上下文。
{% for team in teams %}
<h3><a href='/teams/{{ team.id }}'>{{team.name}}</a></h3>
{% endfor %}
答案 1 :(得分:0)
queryset = UserTeams.objects.filter(teamID__owner=request.user)
这会过滤UserTeams
owner = current user
个对象