2011-06-28 34 views
-1

爲什麼下面的返回結果:Django的過濾器提供了意外的結果

>>> 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

在你的模型看,它看起來像你應該在你的查詢中使用legacy_id而不是id

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

(注:看來,你的數據庫中有一個primary id字段和一個legacy_id字段,實際上你不需要在你的模型中手動設置ID字段,因爲Django會自動爲你做這件事。 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/

+0

3128是您的團隊ID還是legacy_id? –

+0

'legacy_id'可能相關也可能不相關。表中沒有該名稱的列,執行您建議的查詢將返回任何結果。我寧願認爲它是以前代碼迭代的遺留物。如果我在這個假設中錯了,我將它包括在內。 –

+0

@ Felipe Cruz:3128是團隊'id'。 –

0

嘗試,如果這個工程:

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

+0

即產率:_TypeError: 'INT' 對象不是iterable_。此外,即使這種方法的改進有效,我也可能無法使用它。我正在CLI中進行測試,但由於數據在應用程序本身中傳遞的方式,因此必須使用標準過濾器字符串。 –