The django-tables2 docs describe how to sort a custom column (https://django-tables2.readthedocs.io/en/latest/pages/ordering.html#table-order-foo-methods). But I can't figure out how to apply this to my situation and am hoping someone can help.
Before sharing code, here's what I'm doing. The table is built of django-auditlog LogEntry instances. Each row in the table is a LogEntry instance. The custom column is a property of the object that changed (ie, caused this LogEntry to be created). For example suppose a student object changed, the custom column will show 'student.'
Here's how I render the column. FWIW, what auditlog does is it references the content types table by id and the id of the instance. My code simply follows that trail to get the right instance. On the instance there's a method (my_category()) which produces the right "main category" text.
@staticmethod
def render_major_category(record):
try:
changed_object = ChangeTable.get_changed_object(record)
answer = changed_object.my_category().capitalize()
except ObjectDoesNotExist:
answer = "No data"
return answer
@staticmethod
def get_changed_object(record):
changed_object_type = record.content_type
try:
changed_object = changed_object_type.get_object_for_this_type(id=record.object_id)
except ObjectDoesNotExist:
raise ObjectDoesNotExist(str(changed_object_type))
return changed_object
The django-tables2 doc's say to annotate the queryset in a method a la:
def order(self, queryset, is_descending):
queryset = queryset.annotate(
amount=F("shirts") + F("pants")
).order_by(("-" if is_descending else "") + "amount")
return (queryset, True)
What I don't understand is how to use the functions I used for render_major_category in the annotate() method. As in annotate(my_category=something?)??
Everything I've found are aggregations or direct references to properties (like above). One of the solutions I found suggests creating a property on the class. However, I would prefer not to create a special extension or proxy to auditlog LogEntry just for this.
Thanks.