Django Querysets:从set中只获取一个并对它们进行排序

时间:2017-07-24 03:57:14

标签: django django-queryset

我有这个型号:

#models.py

class Expression(models.Model):
    text = models.CharField(max_length=254)

class Country(models.Model):
    name = models.CharField(max_length=100)

class Definition(models.Model):
    expression = models.ForeignKey(Expression)
    country = models.ForeignKey(Country)
    text = models.CharField(max_length=254)

class Vote(models.Model):
    definition = models.ForeignKey(Definition)

这个观点

#views.py

def index(request):
    # Here is where I want to get the queryset
    return render(request, 'index.html', { 'definitions':definitions)

然后在模板中,这个想法是这样的:

#index.html


Expression is {{ expression }}
{% for definition in expressions.definitions_set.all %}
    Country's "1" top definition for expression is {{ definition }}
    Country's "2" top definition for expression is {{ definition }}
    [etc]
{% endfor %}

如何获得仅获得每个国家/地区的最高定义(通过投票)的定义查询集

1 个答案:

答案 0 :(得分:0)

django docs link

您可以使用order_with_respect_toDefinition进行排序。

class Definition(models.Model):
    expression = models.ForeignKey(Expression)
    country = models.ForeignKey(Country)
    text = models.CharField(max_length=254)

    class Meta:
        order_with_respect_to = 'country'

也许我认为我可以像上面那样做。