Django 1.8:在ModelAdmin的重写方法get_query_set()中过滤query_set

时间:2016-03-26 10:07:32

标签: python django python-3.x django-admin

考虑一个班级和代理人:

class EchangeVoisin(VoisinModel):
    class Meta(VoisinModel.Meta):
        pass
...
    typeechange = models.SmallIntegerField(choices = TYPEECHANGE, verbose_name = 'Type')
...

class PropositionDon(EchangeVoisin):
    class Meta(EchangeVoisin.Meta):
        proxy = True;
    def __init__(self, *args, **kwargs):
        super(EchangeVoisin, self).__init__(*args, **kwargs)
        self.typeechange = self.TYPEDON

过滤器在shell中运行良好:

>>> EchangeVoisin.objects.all()
[<EchangeVoisin: Livre de recettes>, <EchangeVoisin: des chaussures de sécurité>, <EchangeVoisin: Sac à main>]
>>> EchangeVoisin.objects.all().filter(typeechange=EchangeVoisin.TYPEDON)
[<EchangeVoisin: Sac à main>]
>>>

>>> PropositionDon.objects.all()
[<PropositionDon: Livre de recettes>, <PropositionDon: des chaussures de sécurité>, <PropositionDon: Sac à main>]
>>> PropositionDon.objects.filter(typeechange = 0)
[<PropositionDon: Sac à main>]

但不在ModelAdmin中,查询集未被过滤,网格包含所有记录......

class EchangeAdmin(admin.ModelAdmin):
...
...
    pass

class PropositionDonAdmin(EchangeAdmin):
...
...
    def get_queryset(self, request):
        qs = super(PropositionDonAdmin,self).get_queryset(request)
        qs.filter(donateur = None)
        return qs
    pass

我确定调用了overriden方法,似乎框架没有使用返回的queryset ......是否有任何问题

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

filter不会改变调用它的查询集,它会返回一个新的查询集。您需要返回该新查询集:

def get_queryset(self, request):
    qs = super(PropositionDonAdmin,self).get_queryset(request)
    qs = qs.filter(donateur = None)
    return qs