[Answer]-Alphabetically order values in a Many-to-Many relation, then list_display the first item

1đź‘Ť

âś…

Well, you could define a series of custom methods on the ModelAdmin, each of which returns the speaker at position X. But this would be horribly inefficient from the database point of view (each column would require a separate lookup) and not be very extensible.

Could you just have the speakers as a comma-separated list of names? That would be easy, again via a custom method:

class TalkAdmin(admin.ModelAdmin):

    list_display = ['title', 'get_speakers', 'date']

    def get_speakers(self, obj):
        speakers = obj.speakers.all().order_by('name').values_list('name', flat=True)
        return ', '.join(speakers)

0đź‘Ť

For the first point, you can either specifiy the ordering when getting the speakers for a talk, ie:

speakers = talk.speakers.order_by("name")

or set “name” as the default ordering for the Speaker model if that’s your common use case, ie:

class Speaker(models.Model):
    # your code here
    class Meta:
        ordering = ("name",)

For the second point since each talk can have from zero to virtually billions of speakers you cannot seriously expect to have one column per speaker… What you can do is add some method to your ModelAdmin class that returns a comma-separated (or whatever) list of speakers for each Talk so you still only have one single field. How to do this is fully documented here : https://docs.djangoproject.com/en/1.5/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display

Leave a comment