覆盖构建过滤器侧边栏的查询集

发布于 2024-08-31 17:05:42 字数 678 浏览 3 评论 0原文

我正在编写一个曲棍球数据库/管理器。所以我有以下模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

◇流星雨 2024-09-07 17:05:42

有趣的问题。处理这类事情要做的第一件事就是查看来源,通常都有很好的评论。

看起来 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 method get_changelist, which returns a class to use to create the changelist page. By default, that simply returns the ChangeList class from django.contrib.admin.views.main. In turn, that class has a method get_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 overwritten get_filters method that only returns the values you want. Then, in your ModelAdmin subclass, overwrite get_changelist to return your ChangeList subclass (note, you need to return the class itself, not an instance).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文