Django Admin: Order by value on related Foreign Key(Django Admin:按相关外键的值排序)
问题描述
我正在尝试按对象相关外键集中的特定值对 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:按相关外键的值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Django Admin:按相关外键的值排序
基础教程推荐
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01