Reverse loopup for admin_order_field?

9 views
Skip to first unread message

Mark Phillips

unread,
Nov 21, 2019, 10:54:34 AM11/21/19
to django users
I have two models
class Document(Model):
    document_id = models.AutoField(primary_key=True)
    ... other fields

class DocumentMetaData(Model):
    documentMetaData_id = models.AutoField(primary_key=True)
    document_id = models.ForeignKey(Document, on_delete=models.CASCADE, verbose_name="document file name")
    metadata = JSONField(blank=True)


The metadata in the DocumentMetaData model has a key 'Decade' in the JSONField.

In the DocumentMetaDataAdmin I have this for a sortable Decade field:
    def get_decade(self, obj):
        return obj._decade
    get_decade.admin_order_field = '_decade'

I would like to have a get_decade function in the DocumentAdmin that displays a Decade column in the DocumentAdmin page, and have that field sortable. So far, I can get the Decade column in the DocumentAdmin by doing this:
    def get_decade(self, obj):
        result = DocumentMetaData.objects.get(document_id=obj.document_id).metadata['Decade']
        return result
    get_decade.admin_order_field = 'get_decade'


But the sorting part does not work - I get a field error as there is no decade field in the Document model. Is there some way to do a reverse lookup on the document_id field to the DocumentMetaData model (since admin_order_field needs a related model) so I can sort on the decade field in the DocumentAdmin?

Thanks!

Mark

Reply all
Reply to author
Forward
0 new messages