简体   繁体   中英

Django 1.8 : Filter query_set in overriden method get_query_set() of ModelAdmin

considering a class and a proxy :

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

filter works fine in 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>]
>>>

or

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

but not in ModelAdmin, the query set is not filtered, the grid contains all the records ...

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

I'm sure the overriden method is called, it seems the queryset returned is not used by the framework... Is there any issue

Many thanks for you help !

filter does not mutate the queryset it is called on, it returns a new one. You need to return that new queryset:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM