覆盖构建过滤器侧边栏的查询集
我正在编写一个曲棍球数据库/管理器。所以我有以下模型:
class Team(models.Model):
name = models.CharField(max_length=60)
class Game(models.Model):
home_team = models.ForeignKey(Team,related_name='home_team')
away_team = models.ForeignKey(Team,related_name='away_team')
class SeasonStats(models.Model):
team = models.ForeignKey(Team)
好的,我的问题如下。有很多球队,但统计数据仅针对我的俱乐部进行管理。因此,如果我在管理后端使用“list_display”,我想修改/覆盖构建侧边栏进行过滤的查询集,以仅将我们的主队显示为过滤器选项。
这在 Django 中可能吗?
我已经制作了这样的自定义表单
class SeasonPlayerStatsAdminForm(forms.ModelForm):
team = forms.ModelChoiceField(Team.objects.filter(club__home=True))
所以现在只是缺少过滤。有什么想法吗?
I'm writing a hockey database/manager. So I have the following models:
class Team(models.Model):
name = models.CharField(max_length=60)
class Game(models.Model):
home_team = models.ForeignKey(Team,related_name='home_team')
away_team = models.ForeignKey(Team,related_name='away_team')
class SeasonStats(models.Model):
team = models.ForeignKey(Team)
Ok, so my problem is the following. There are a lot of teams, but Stats are just managed for my Club. So if I use "list_display" in the admin backend, I'd like to modify/overwrite the queryset which builds the sidebar for filtering, to just display our home teams as a filter option.
Is this somehow possible in Django?
I already made a custom form like this
class SeasonPlayerStatsAdminForm(forms.ModelForm):
team = forms.ModelChoiceField(Team.objects.filter(club__home=True))
So now just the filtering is missing. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有趣的问题。处理这类事情要做的第一件事就是查看来源,通常都有很好的评论。
看起来
ModelAdmin
有一个方法get_changelist
,它返回一个用于创建更改列表页面的类。默认情况下,它只是从 django.contrib.admin.views.main 返回 ChangeList 类。反过来,该类有一个方法get_filters
,它似乎是返回过滤器侧边栏值的方法。因此,您需要做的是创建一个
ChangeList
子类,其中包含覆盖的get_filters
方法,该方法仅返回您想要的值。然后,在您的ModelAdmin
子类中,覆盖get_changelist
以返回您的 ChangeList 子类(注意,您需要返回类本身,而不是实例) 。Interesting question. The first thing to do with this sort of thing is to look at the source, which is usually very well-commented.
It looks like
ModelAdmin
has a methodget_changelist
, which returns a class to use to create the changelist page. By default, that simply returns theChangeList
class fromdjango.contrib.admin.views.main
. In turn, that class has a methodget_filters
which appears to be the one that returns the values for the filter sidebar.So, what you would need to do is to create a
ChangeList
subclass with an overwrittenget_filters
method that only returns the values you want. Then, in yourModelAdmin
subclass, overwriteget_changelist
to return your ChangeList subclass (note, you need to return the class itself, not an instance).