[Answered ]-Filter query based on user in Django Admin

2👍

In your EggAdmin, you must override queryset method

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

UPDATE: Ok, that change everything… On SuperPrifile admin, when you open a SuperProfile record, you wish eggs_unlocked to be filtered according to that user… So:

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)

I know, using regex to grab the object id is a really bad practise, but as i mention, that is the only way to do this as i know.

And here is the doc for formfield_for_manytomany

👤Mp0int

0👍

Eggs.objects.filter(kitchens=profile.my_kitchen)

Leave a comment