Django过滤器提供意外的结果

时间:2011-06-28 17:10:06

标签: python django django-models

为什么以下内容不会返回结果:

>>> count = PlayerYear.objects.filter(team__id=3128).count()
>>> count # Output: 0

但这回归32(今年在法拉格特海军上将学院足球队的球员数量):

>>> count = PlayerYear.objects.filter(team__id=1).count()
>>> count # Output: 32

给出下表(teams_team):

---------------------------------------------------------
|  id  | school_id |       admin_display                |
---------------------------------------------------------
| 3128 |     1     | Admiral Farragut Academy: Football |

以下(缩写)模型:

class PlayerYear(models.Model):
    player = models.ForeignKey(Player)
    team = models.ForeignKey(Team)
    # snip

class Team(models.Model):
    legacy_id = models.IntegerField(blank=True, null=True)
    school = models.ForeignKey(School)
    # snip

class School(models.model):
    legacy_id = models.IntegerField(blank=True, null=True)
    school = models.CharField(max_length=255, blank=True, null=True)
    # snip

我不明白为什么在提供school_id值时会得到结果,即使我将team__id指定为过滤器。如何使用团队ID(3128)获得结果?

2 个答案:

答案 0 :(得分:2)

查看您的模型,看起来您应该在查询中使用legacy_id而不是id

count = PlayerYear.objects.filter(team__legacy_id=3128).count()

(注意:您的数据库中似乎同时包含主ID字段和legacy_id字段。实际上您不需要在模型中手动设置ID字段,因为Django会自动为您执行此操作。 docs:If you don't specify primary_key=True for any fields in your model, Django will automatically add an IntegerField to hold the primary key, so you don't need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior.

https://docs.djangoproject.com/en/dev/topics/db/models/

答案 1 :(得分:0)

尝试这是否有效:

>>> count = PlayerYear.objects.filter(team=Team.objects.get(3128)).count()