我有一个模型UserSelect
class UserSelect(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
bowler = models.ForeignKey(Bowlers, on_delete=models.CASCADE, related_name='bowlers', null=True, blank=True)
batsman = models.ForeignKey(Batsmen, on_delete=models.CASCADE, related_name='batsman', null=True, blank=True)
team = models.IntegerField(blank=True, default='1')
这是使用外键指向我的两个常礼帽和击球手的模型
我在视图中将此模型值称为
def team(request, pk):
user_sel = UserSelect.objects.filter(user=request.user, team=pk)
context = {
'user_sel': user_sel,
}
return render(request, 'team_analysis.html', context)
在这里,我通过给出pk来获取所有对象,但是如何在视图中通过它访问其他两个模型投球手和击球手的数据呢?
答案 0 :(得分:0)
您可以在这样的视图中访问它们:
for user in user_sel:
print(user.bowler) # bowler model object
print(user.batsman) # batsman model object
您也可以在模板中访问它们:
{% for user in user_sel %}
{{ user.bowler }}
{{ user.bowler.pk }}
{{ user.batsman }}
{{ user.batsman.pk }}
{% endfor %}