Ticket #2884: get_query_set.patch

File get_query_set.patch, 2.1 KB (added by bangcok_dangerus ( at ] hotmail.com, 18 years ago)

fixes the issue, could do with more testing

  • django/contrib/admin/views/main.py

     
    669669        return order_field, order_type
    670670
    671671    def get_query_set(self):
     672        def follow_fkey_ordering(field, fields_seen = None):
     673            fields_seen = fields_seen or []
     674            related_object = field.rel.to
     675            ordering = related_object._meta.ordering
     676            if ordering:
     677                ordering_field = related_object._meta.get_field(ordering[0])
     678                if isinstance(ordering_field.rel, models.ManyToOneRel) and not (field in fields_seen):
     679                    fields_seen.append(field)
     680                    rel_table, rel_ordering = follow_fkey_ordering(ordering_field, fields_seen)
     681                else:
     682                    rel_ordering = ordering_field.column
     683                    rel_table = related_object._meta.db_table
     684            else:
     685                rel_ordering = related_object._meta.pk.column
     686                rel_table = related_object._meta.db_table
     687            return rel_table, rel_ordering
     688
    672689        qs = self.manager.get_query_set()
    673690        lookup_params = self.params.copy() # a dictionary of the query string
    674691        for i in (ALL_VAR, ORDER_VAR, ORDER_TYPE_VAR, SEARCH_VAR, IS_POPUP_VAR):
     
    706723                # For OneToOneFields, don't try to order by the related object's ordering criteria.
    707724                pass
    708725            elif isinstance(f.rel, models.ManyToOneRel):
    709                 rel_ordering = f.rel.to._meta.ordering and f.rel.to._meta.ordering[0] or f.rel.to._meta.pk.column
    710                 lookup_order_field = '%s.%s' % (f.rel.to._meta.db_table, rel_ordering)
     726                #Recursively follows ForeignKey fields to get the correct table name and field for order_by.
     727                ordering_table, ordering_field = follow_fkey_ordering(f)
     728                lookup_order_field = '%s.%s' % (ordering_table, ordering_field)
    711729
    712730        # Set ordering.
    713731        qs = qs.order_by((self.order_type == 'desc' and '-' or '') + lookup_order_field)
Back to Top