yarbelk
yarbelk

Reputation: 7715

Filter query based on user in Django Admin

I am trying to filter a m-2-m based on some 3 way relational logic. I have the following models (example only... but the more I write it, it looks like a game I'd like to play...) Forgive my over use of the spam and eggs metavariables...

Models:

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')

Question: As an administrator, in someone else's SuperProfileAdmin:

I'm not sure if this is clear, please comment on what needs clarification.

Upvotes: 1

Views: 1118

Answers (2)

Mp0int
Mp0int

Reputation: 18727

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

Upvotes: 2

acid_crucifix
acid_crucifix

Reputation: 362

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

Upvotes: 0

Related Questions