1

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

楷模:

class SuperProfile(models.Model):
    user = models.ForgeignKey('User')
    eggs_unlocked = models.ManyToMany('Egg')
    my_kitchen = models.ForeignKey('SuperKitchen')

class SuperKitchen(models.Model):
    name = models.CharField(max_length=20)

class Egg(models.Model):
    eggyness = models.PostiveIntegerField(help_text=_("how Eggy it is. eg." 
                                                      "Spam'n'Eggs is over 9000")
    kitchens = models.ForeignKey(help_text=_('What kitchen carries this')

问题:作为管理员,在别人的SuperProfileAdmin 中:

  • 我想根据他们所属的内容列出eggs他们可以使用的内容kitchen
  • 一个人Kitchen,永远不会变。
  • Eggs只出现在一个kitchen
  • 您如何获得SuperProfileSuperKitchen过滤所述其他用户Egg的列表的实例

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

4

2 回答 2

2

在你的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 管理员上,当您打开 SuperProfile 记录时,您希望eggs_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 是一种非常糟糕的做法,但正如我所提到的,这是我所知道的唯一方法。

这是formfield_for_manytomany的文档

于 2012-05-18T09:34:24.143 回答
0
Eggs.objects.filter(kitchens=profile.my_kitchen)
于 2012-05-18T10:14:31.153 回答