开发者

Django Filter Provides Unexpected Results

开发者 https://www.devze.com 2023-03-16 12:15 出处:网络
Why does the following return no results: >>> count = PlayerYear.objects.filter(team__id=3128).count()

Why does the following return no results:

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

But this returns 32 (the number of players this year on the Admiral Farragut Academy Football team):

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

Given the following table (teams_team):

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

And the following (abbreviated) models:

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

and

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

and

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

I do not understand why I get results when providing开发者_如何学JAVA the school_id value, even though I specified team__id as the filter. How can I get results using the Team ID (3128)?


Looking at your models it looks like you should be using legacy_id in your query rather than id:

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

(Note: It appears that you have both a primary id field, and a legacy_id field in your database. You actually don't need to set ID fields manually in your models, since Django automatically does this for you. From the 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/


try if this works:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消