开发者

Looping over related (M2M) items in the order specified by the intermediatry relationship

Using the example from the docs: https://docs.djangoproject.com/en/1.2/topics/db/models/#intermediary-manytomany

I can loop over the groups and show the people in each:

{% for group in group_list %}
 {{ group.name }}:
 {% for member in group.members.all %}
  {{ member.name }}
 {% endfor %}
{% endfor %}

But I can't figure out how to show the members in the order they joined (i.e., by membership.date_joined). Using dictsort after the all like so:

{% for member in group.members.all|dictsort:"date_jo开发者_运维百科ined" %}

results in an empty member list. And I've tried using members.through, but can't seem to get any data from that, either.


You can specify the ordering attribute in the model's Meta -- then all queries on that model will be ordered that way by default.

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

    class Meta:
        ordering = ['date_joined']


Found a work around:

In the model for class Group, I added a method

def members_by_date(self):
 return Membership.objects.filter(group = self).order_by('date_joined')

And in the template:

{% for membership in group.members_by_date %}
 {{ membership.person.name }}

I would still like to know how to do on-the-fly ordering in the template, though, using dictsort or otherwise, if anyone has a hint for that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜