如何通过其外键字段订购相关字段?

时间:2017-07-25 22:14:44

标签: django django-models django-serializer

我们假设我有三个模型如下;

class Stats(models.Model):
    gp = models.IntegerField(default=0)
    won = models.IntegerField(default=0)
    drawn = models.IntegerField(default=0)
    lose = models.IntegerField(default=0)
    gf = models.IntegerField(default=0)
    ga = models.IntegerField(default=0)
    gd = models.IntegerField(default=0)
    pts = models.IntegerField(default=0)

class Team(models.Model):
    team_name = models.CharField(max_length=50)
    stats = models.ForeignKey(Stats)

class Group(models.Model):
    group_name = models.CharField(max_length=1)
    teams = models.ManyToManyField(Team)

而且,这是我的Group Model

序列化器
class GroupSerializer(serializers.ModelSerializer):
    teams = TeamSerializer(read_only=True, many=True)

    class Meta:
        model = Group
        fields = '__all__'

但是,我想根据他们的统计数据的pts和gd字段订购团队。我尝试将order_with_respect_to='stats'添加到团队模型,将ordering = ['pts', 'gd']添加到统计模型,但它不起作用。

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

class Team(models.Model):
    team_name = models.CharField(max_length=50)
    stats = models.ForeignKey(Stats)

    class Meta:
        ordering = ['stats__pts', 'stats__gd']