django通过字段排序object_list

时间:2011-04-12 12:52:28

标签: django django-models

说我有一个好老人/团体/会员关系

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __unicode__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __unicode__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

我想要一个通用视图,它显示属于一个组(在URL中指定)的人员列表,这些人员按Membership类的date_joined字段排序。我想我可以像这样做一个视图

def group_list(request, pagina):
    return list_detail.object_list(
        request,
        queryset = Person.objects.filter(group__name = slug),
        template_object_name = 'person',
        extra_context = { 'membership' : Membership.objects.all() }, 

        )

然后只需通过membership__date_joined访问模板中的date_joined但没有运气

2 个答案:

答案 0 :(得分:1)

您真正想要做的是从Membership对象开始。对于Person和Group的特定组合,这是唯一的独特之处 - 如果您从Person开始,正如您所做的那样,访问其成员资格会为您提供所有,而不是您想要的那个 。所以:

return list_detail.object_list(
    request,
    queryset = Membership.objects.filter(group__name = slug),
    template_object_name = 'membership',
)

现在在你的模板中:

{% for member in membership %}
    {{ member.person.name }}: {{ member.date_joined }}
{% endif %}

答案 1 :(得分:0)

一种选择是直接过滤中间模型:

members = [member.person for member in Membership.objects.filter(group__name=slug).order_by('-date_joined')]

或只是members = Membership.objects.filter(group__name=slug).order_by('-date_joined')

然后你在模板中迭代这个列表,如下所示:

{% for member in members %}
    {{ member.person.name }} : {{ member.date_joined }}
{% endfor %}