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

Getting an specific field of a model with a 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 是外键

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

for bet in z:
    print bet.match_id

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

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