Ticket #16311: patch_list_filter_limit_to_related.diff

File patch_list_filter_limit_to_related.diff, 2.5 KB (added by Stanislas Guerra <stan@…>, 13 years ago)

Patch for django 1.3

  • django/db/models/fields/__init__.py

     
    356356    def get_validator_unique_lookup_type(self):
    357357        return '%s__exact' % self.name
    358358
    359     def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
     359    def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to={}):
    360360        """Returns choices with a default blank choices included, for use
    361361        as SelectField choices for this field."""
    362362        first_choice = include_blank and blank_choice or []
    363363        if self.choices:
    364364            return first_choice + list(self.choices)
    365365        rel_model = self.rel.to
     366        if not limit_choices_to:
     367            limit_choices_to = self.rel.limit_choices_to
    366368        if hasattr(self.rel, 'get_related_field'):
    367             lst = [(getattr(x, self.rel.get_related_field().attname), smart_unicode(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)]
     369            lst = [(getattr(x, self.rel.get_related_field().attname), smart_unicode(x)) for x in rel_model._default_manager.complex_filter(limit_choices_to)]
    368370        else:
    369             lst = [(x._get_pk_val(), smart_unicode(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)]
     371            lst = [(x._get_pk_val(), smart_unicode(x)) for x in rel_model._default_manager.complex_filter(limit_choices_to)]
    370372        return first_choice + lst
    371373
    372374    def get_choices_default(self):
  • django/contrib/admin/filterspecs.py

     
    8080        self.lookup_val = request.GET.get(self.lookup_kwarg, None)
    8181        self.lookup_val_isnull = request.GET.get(
    8282                                      self.lookup_kwarg_isnull, None)
    83         self.lookup_choices = f.get_choices(include_blank=False)
     83        limit_choices_to = {}
     84        if getattr(model_admin, '%s_filter_related_only' % f.name, False):
     85            limit_choices_to['pk__in'] = set(model_admin.queryset(request).values_list(f.name, flat=True))
     86        self.lookup_choices = f.get_choices(include_blank=False, limit_choices_to=limit_choices_to)
    8487
    8588    def has_output(self):
    8689        if isinstance(self.field, models.related.RelatedObject) \
Back to Top