J Marchini
J Marchini

Reputation: 3

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 !

Upvotes: 0

Views: 47

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599450

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

Upvotes: 1

Related Questions