Django admin: sorted by corresponding foreign key

I am trying to sort a Django administrators list page by a specific value in a corresponding external set of objects.

In particular, in the code below, I want the ContentAdmin view to display a list of all content objects sorted by "Twitter Score" value (Score object named "Twitter").

In a django application, I have the following models:

class Content(models.Model):
    body = models.CharField(max_length=564)
    title = models.CharField(max_length=64) 

class Score(models.Model):
    name = models.CharField(max_length=64)
    score = models.IntegerField()
    content = models.ForeignKey('Content')

And in admin.py I have the following:

class ContentAdmin(admin.ModelAdmin):
    list_display = ('title', 'show_twitter_score',)

    def show_twitter_score(self, obj):
        twitter_score = obj.score_set.get(name='Twitter')
        return 'Twitter: ' + str(twitter_score.score)

PURPOSE: Admin panel for ContentAdmin displays content objects sorted by Twitter account

Thanks everyone!

+5
source share
3 answers

, get_queryset ContentAdmin. ORM

def get_queryset(self, request):
    qs = super(ContentAdmin, self).get_queryset(request)
    return qs.filter(score__name='Twitter').order_by('-score__score')

Django 1.5 queryset.

def queryset(self, request):
    qs = super(ContentAdmin, self).queryset(request)
    return qs.filter(score__name='Twitter').order_by('-score__score')
+4

, ModelAdmin.list_display Django:

list_display, , ( Django ).

, list_display , , admin_order_field .

:

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    color_code = models.CharField(max_length=6)

    def colored_first_name(self):
        return '<span style="color: #%s;">%s</span>' % (self.color_code, self.first_name)
    colored_first_name.allow_tags = True
    colored_first_name.admin_order_field = 'first_name'

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'colored_first_name')

, Django first_name _first_name .

.

0

django admin db , , .

, , , , django , , .

, queryset.

:)

Content.objects.all().extra(select={'twitter_score': 'SELECT score from content_score WHERE content_score.id = content_content.id'})

:

Content.objects.all(). extra (select = {'twitter_score': 'SELECT' Twitter: '|| content_score WHERE content_score.id = content_content.id'})

0

All Articles