问题描述
我正在尝试按对象相关外键集中的特定值对 Django 管理列表页面进行排序.
I'm trying to sort a Django Admin list page by a specific value in the objects' related foreign key set.
具体来说,在下面的代码中,我希望 ContentAdmin 视图显示按Twitter Score"排序的所有内容对象的列表(名为Twitter"的 Score 对象).
Specifically, in the below code, I want the ContentAdmin view to show a list of all content objects sorted by the "Twitter Score" (The Score object with name "Twitter").
在 django 应用中,我有以下模型:
In the django app 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')
在 admin.py 我有以下内容:
And in the 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)
目标:ContentAdmin 的管理面板显示按Twitter"分数排序的内容对象
GOAL: The admin panel for ContentAdmin displays the content objects ordered by "Twitter" scores
谢谢大家!
推荐答案
我通过扩展 ContentAdmin
类的 get_queryset
方法解决了这个问题.之后,只需获取正确的 ORM 查询即可
I solved this by extending the get_queryset
method of the ContentAdmin
class. After that, it was just a matter of getting the right ORM query
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
.
For Django 1.5 and earlier, the method was queryset
.
def queryset(self, request):
qs = super(ContentAdmin, self).queryset(request)
return qs.filter(score__name='Twitter').order_by('-score__score')
这篇关于Django Admin:按相关外键的值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!