【问题标题】:How to display a filtered admin list based off of a count of foreign keys in django如何根据 django 中的外键计数显示过滤的管理员列表
【发布时间】:2012-07-13 12:04:08
【问题描述】:

我正在尝试为我的管理视图定义一个代理模型,并让它只显示具有一定数量外键值的对象。

这是我正在尝试的,但我无法过滤 yVotes:

class Post(models.Model):
    title = models.CharField(max_length=512)

class PostVote(models.Model):
    post = models.ForeignKey(Post)
    vote = models.CharField(max_length=1)

class VotedPost(models.Post):
    def _yVotes(self):
        return models.PostVote.objects.filter(post=self, vote='Y').count()
    yVotes = property(_yVotes)
    class Meta:
        proxy = True 

class VotedPostAdmin(PostAdmin):
    list_display = ('title', 'yVotes')
    def queryset(self, request):
        return self.model.objects.filter(yVotes__gt=0)

所以我的最终结果是,当您浏览到 VotedPost 的 /admin 页面时,它只会显示投票数超过 0 的帖子。注释掉 VotedPostAdmin 中的查询集,yVotes 的正确值将显示在 list_display 中。

提前致谢!

【问题讨论】:

    标签: django django-models django-admin django-queryset


    【解决方案1】:

    为什么不覆盖 get_queryset 或使用管理过滤器来创建这样的显示。你正在尝试做的事情似乎过于复杂 tbh

    class PostAdmin(admin.ModelAdmin):
        def queryset(self, request):
            qs = super(ThisAdmin, self).queryset(request)
            # do stuff and return whatever
    

    【讨论】:

    • 我可以简化事情,只是不确定如何获得我想要的结果。我才刚接触 django 一个星期,所以还在学习。我们希望有两个不同的管理员链接,一个用于所有帖子,一个用于投票帖子。我正在调查管理员过滤器路由。
    【解决方案2】:

    这是迄今为止我最终得到的解决方案,可以让我获得所需的结果。如果有人有更优雅的解决方案,我将等待接受:

    class VotedPostAdmin(PostAdmin):
        list_display = ('title', 'yVotes')
        def queryset(self, request):        
        return VotedPost.objects.all().annotate(count = Count('postvote')).order_by('-count').filter(count__gt=0).filter(postvote__vote='Y')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 2011-01-29
      • 1970-01-01
      • 2018-09-20
      • 2011-01-23
      • 1970-01-01
      • 2016-03-10
      相关资源
      最近更新 更多