Reputation: 7715
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...
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')
eggs
they can use based on what kitchen
they are part ofKitchen
doesn't change, ever. Eggs
only appear in one kitchen
.SuperProfile
or SuperKitchen
to filter the Egg
list for said other userI'm not sure if this is clear, please comment on what needs clarification.
Upvotes: 1
Views: 1118
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