3

我有两个具有多对多关系的模型。这是代码:

class Player(models.Model):
    SEX_CHOICES = (
        ('f', 'Female'),
        ('m', 'Male'),
    )
    tournaments = models.ManyToManyField('Tournament', through = "PlayerTournament",verbose_name = u"Tournament's players")
    first_name = models.CharField(max_length = 30, verbose_name = u"First name")
    last_name = models.CharField(max_length = 50, verbose_name = u"Last name")
    sex = models.CharField(max_length = 1, choices = SEX_CHOICES, default = 'f', verbose_name = u"Sex")
    elo = models.IntegerField(verbose_name = u"ELO")

    class Meta:
        ordering = ['elo']

    def __unicode__(self):
        return "%s - %s" % (self.last_name, self.first_name)

class Tournament(models.Model):
    title = models.CharField(max_length = 100, verbose_name = u"Tournament's title")
    players = models.ManyToManyField('Player', through = "PlayerTournament",verbose_name = u"Tournament's players")
    beginning_date = models.DateTimeField(verbose_name = u"Tournament's beginning", null=True, blank = True)

    def __unicode__(self):
        return self.title

class PlayerTournament(models.Model):
    player = models.ForeignKey(Tournament)
    tournament = models.ForeignKey(Player)

    class Meta:
        db_table ='game_player_tournaments'
        auto_created = Player

我正在尝试进行查询以获取相关字段

PlayerTournament.objects.filter(tournament__title = "Winter").values()

但它不起作用

FieldError: Cannot resolve keyword 'title' into field. Choices are: elo, first, first_name, id, last_name, playertournament, second, sex, statistics, tournament, tournaments

我究竟做错了什么?

4

1 回答 1

5

查看您的模型:

class PlayerTournament(models.Model):
    player = models.ForeignKey(Tournament)
    tournament = models.ForeignKey(Player)

你有playertournament互换

你应该这样做:

PlayerTournament.objects.filter(player__title = "Winter").values()

如果您确实在寻找相关领域,您应该使用select_relatedorprefetch_related代替values(根据您的查询,我非常怀疑)

于 2013-11-08T21:52:05.843 回答