Python Django Admin中基于用户的筛选查询

Python Django Admin中基于用户的筛选查询,python,django,django-admin,Python,Django,Django Admin,我正在尝试根据一些3路关系逻辑过滤一个m-2-m。我有以下模型(仅示例…但我写得越多,它看起来就像我想玩的游戏…)请原谅我过度使用spam和eggs元变量 模型: 问题:作为管理员,在其他人的超级profileadmin中: 我想根据它们是厨房的一部分列出它们可以使用的鸡蛋 一个人的厨房永远不会改变 鸡蛋只出现在一个厨房 如何获取超级profile或超级厨房的实例,以过滤所述其他用户的鸡蛋列表 我不确定这是否清楚,请评论需要澄清的内容。在您的EggAdmin中,您必须重写queryset方法

我正在尝试根据一些3路关系逻辑过滤一个m-2-m。我有以下模型(仅示例…但我写得越多,它看起来就像我想玩的游戏…)请原谅我过度使用
spam
eggs
元变量

模型: 问题:作为管理员,在其他人的超级profileadmin中:
  • 我想根据它们是厨房的一部分列出它们可以使用的
    鸡蛋
  • 一个人的厨房永远不会改变
  • 鸡蛋
    只出现在一个
    厨房
  • 如何获取
    超级profile
    超级厨房
    的实例,以过滤所述其他用户的
    鸡蛋
    列表

我不确定这是否清楚,请评论需要澄清的内容。

在您的
EggAdmin
中,您必须重写
queryset
方法

class EggAdmin(admin.ModelAdmin):
    ...
    def queryset(self, request):
        kitchen = request.user.superprofile_set.get().my_kitchen #get related users kitchen
        qs = super(EggAdmin, self).queryset(request) #call original queryset method that you are overriding
        return qs.filter(kitchens=kitchen) #apply your filter
更新:好的,这改变了一切。。。在SuperPrifile admin上,当您打开SuperPrifile记录时,您希望根据该用户过滤
egs\u unlocked
。。。因此:

import re
# grab the superprofile id from the url
sup_pro_rgx=re.compile(r'(\d+)')
sup_pro = sup_pro_rgx.findall(request.META['REQUEST_URI'])[0]
# I know this is really the ugliest way to do this, but there is no other way (at least as far as i know) to do this


class SuperProfileAdmin(admin.ModelAdmin):
...
def formfield_for_manytomany(self, db_field, request, **kwargs):
    if db_field.name == "eggs_unlocked":
        my_kitchen = self.get_object(request, object_id=sup_pro).my_kitchen
        kwargs["queryset"] = Egg.objects.filter(kitchen=my_kitchen)
    return super(SuperProfileAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
我知道,使用正则表达式获取对象id是一种非常糟糕的做法,但正如我所提到的,这是我所知道的唯一方法


这是

的文档,虽然这非常有用,但如果我正在编辑其他人的配置文件,那么,
request.user.superprofile\u set.get()。我的厨房
将返回错误的
厨房
。是否有方法访问已存在模型的预填充值?然后,您将使用该
用户,而不是
请求.user
。但是这段代码是基于您在Egg Admin.Ok上的代码编写的。编辑问题以澄清我在哪里寻找过滤器。如何访问所述
用户
实例。
import re
# grab the superprofile id from the url
sup_pro_rgx=re.compile(r'(\d+)')
sup_pro = sup_pro_rgx.findall(request.META['REQUEST_URI'])[0]
# I know this is really the ugliest way to do this, but there is no other way (at least as far as i know) to do this


class SuperProfileAdmin(admin.ModelAdmin):
...
def formfield_for_manytomany(self, db_field, request, **kwargs):
    if db_field.name == "eggs_unlocked":
        my_kitchen = self.get_object(request, object_id=sup_pro).my_kitchen
        kwargs["queryset"] = Egg.objects.filter(kitchen=my_kitchen)
    return super(SuperProfileAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
Eggs.objects.filter(kitchens=profile.my_kitchen)