Ordering by foreign key field

Issue #49 closed
Nikhil Sardana created an issue

Right now, if I order by a foreign key, the default behavior is that it sorts by the foreign key value. Is there a way to sort by a foreign key field?

For instance, if I click on a column named "User", it should filter by the user's name rather than it's pk.

Comments (3)

  1. Benjamin Riddell

    What do you have in the columns property on your class view?

    In the columns property you can use dot notation to access the foreign key fields.

    E.g.

    columns = [
        'pk',    # Displays and sorts by the pk of each instance in your list of the specified model
        'user',    # If I recall correctly this tries to encode the instance of the user object of the foregin key, I'm not sure what will happen here.
        'user.pk',    # Displays and sorts by the actual pk value of the user instance
        'user.username',    # Display and sort by the username value of the user
        'user.email',    # Display and sort by the username value of the user
    ]
    

    I don't think it is needed to answer your question but it might be relevant. You can sort by one attribute but display another by overriding the render_column(self, row, column). E.g. to display the username but sort by the pk

    columns = [
        'user.pk',    # This will be used for sorting and searching
    ]
    
    def render_column(self, row, column):
        if column == 'pk':
            return row.user.username
        else:
            return super(ClassNameOfYourView, self).render_column(row, column)
    
  2. Maciej Wisniowski repo owner

    There is an order_columns parameter that you can use to define an ordering. As noted by @WheatleyNZL you can use dot notation to define columns. Alternatively, you can just override order_columns method.

  3. Log in to comment