使用查询集获取模型的特定字段

时间:2015-04-07 23:33:47

标签: django django-queryset

如果我有这个查询集:

z = Bets.objects.filter(match_id=request.POST['match']).filter(~Q(team_id=request.POST['team']))

我如何获得match_id或team_id?

如果我这样做

  

print z

它显示了我在模型中的unicode,我想要例如

  

print z.match_id

但我得到了QuerySet'对象没有属性' match_id'。 match_id是ForeignKey

1 个答案:

答案 0 :(得分:2)

您应遍历查询集并打印Bet模型的已找到实例的字段:

for bet in z:
    print bet.match_id

如果只有一个对象符合条件,那么您可以使用查询集的get()first()方法:

bet = z.first()
if bet:
    print bet.match_id