Created
December 4, 2012 03:52
-
-
Save grillermo/4200344 to your computer and use it in GitHub Desktop.
Filtering by the properties of a model that has us in an m2m
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.admin import SimpleListFilter | |
from store.models import Box | |
class Items(Model): | |
name = CharField(max_length=200) | |
class Box(Model): | |
items = ManyToManyField(Items) | |
box_color = CharField(max_length=200,choices=( | |
('yellow','yellow'), | |
('green','green'), | |
) | |
# So in my Items admin list i want to filter the items by color, this is my 'failed' attemp. | |
class Items_by_payment_system_filter(SimpleListFilter): | |
title = _('Colors') | |
# Parameter for the filter that will be used in the URL query. | |
parameter_name = 'color' | |
def lookups(self, request, model_admin): | |
""" | |
Returns a list of tuples. The first element in each | |
tuple is the coded value for the option that will | |
appear in the URL query. The second element is the | |
human-readable name for the option that will appear | |
in the right sidebar. | |
""" | |
return Box.colors | |
def queryset(self, request, queryset): | |
# Remember that self.value contains the current selection in the filter options displayed to the user in Admin | |
boxes = Box.objects.filter(items__in=queryset) # get only boxes with the current set of items | |
boxes_ids = boxes.filter(color=self.values()).values_list('items__id',flat=True) | |
return queryset.filter(id__in=boxes_ids) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment