7

オブジェクトの関連する外部キー セットの特定の値で Django 管理リスト ページを並べ替えようとしています。

具体的には、以下のコードでは、「Twitter スコア」(名前が「Twitter」のスコア オブジェクト) でソートされたすべてのコンテンツ オブジェクトのリストを ContentAdmin ビューに表示する必要があります。

django アプリには、次のモデルがあります。

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')

そしてadmin.pyには次のものがあります:

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)

目標: ContentAdmin の管理パネルには、「Twitter」のスコア順に並べられたコンテンツ オブジェクトが表示されます。

みんな、ありがとう!

4

3 に答える 3

5

クラスの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')
于 2012-04-20T21:02:20.747 に答える
1

私が正しく理解していれば、Django のドキュメントのModelAdmin.list_displayからこれを試すことができます。

通常、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')

上記は、admin で color_first_name でソートしようとするときに、first_name フィールドで並べ替えるように Django に指示します。

並べ替えのコードでこの回避策を試すことができます。

于 2012-04-19T19:33:45.287 に答える
-2

django admin は db を使用してソートするため、リストに表示されている関数をソートすることはできません。

できることは、django管理者がモデルをリストするために使用しているクエリセットに表示したい列を追加することです。この方法でソートできます。

必要な列を追加するには、クエリセットの追加メソッドを使用する必要があります。

これでうまくいくはずです:)

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'})

于 2012-04-19T19:53:00.920 に答える