0

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.

1 Answer 1

0

One way to solve this problem is to do the annotation before handing the data to the table. In my view, generic.ListView in this case, each element of the queryset gets augmented with the "annotated" value.

Likely this is because of by django naivete, but it seems annotations target aggregation or summary functions, and not stuff like object references?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.