render_column with choice fields on related fields

Issue #31 resolved
Matthew Pava created an issue

If you specify a choice field directly on a model, render_column will call the get_column_display on the row object to get the string representation of the value. However, it does not do so with a choice field on a related field to the row object.

For instance, let's say I have document model that is related to an invoice model with a choice field of payment methods instantiated by a tuple of 2-tuples. If I create a datatable on the document model and reference 'invoice.payment_method', render_column will show the value instead of the display. This is how I have addressed it in the render_column method. (I replaced "text" with "value".)

    if hasattr(row, 'get_%s_display' % column):
        # It's a choice field
        value = getattr(row, 'get_%s_display' % column)()
    else:
        try:
            value = getattr(row, column)
        except AttributeError:
            obj = row
            parts = column.split('.')
            for part in parts[:-1]:
                if obj is None:
                    break
                obj = getattr(obj, part)

            if hasattr(obj, 'get_%s_display' % parts[-1]):
                obj = getattr(obj, 'get_%s_display' % parts[-1])()
            else:
                obj = getattr(obj, parts[-1])
            value = obj

Comments (2)

  1. Matthew Pava reporter

    Actually, I can compress that code to remove the try..except block and it will behave exactly the same. Whether that's how we want it to behave is an entirely different question.

        obj = row
        parts = column.split('.')
        for part in parts[:-1]:
            if obj is None:
                break
            obj = getattr(obj, part)
    
        if hasattr(obj, 'get_%s_display' % parts[-1]):
            obj = getattr(obj, 'get_%s_display' % parts[-1])()
        else:
            obj = getattr(obj, parts[-1], None)
        value = obj
    
  2. Log in to comment