Django admin - sort by GenericForeignKey's fie

2019-07-10 15:59发布

问题:

I need sort functionality on a GenericForeignKey's field on list display.

models.py

class DealPayment(models.Model):

    product_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    deal = GenericForeignKey('product_type', 'object_id')
    # This deal can be of 'product' or 'certificate'

    payment_date = models.DateTimeField(blank=True, null=True,    help_text="Date when payment is done.")

    transaction_amount = models.DecimalField(max_digits=16, decimal_places=2, default=0,
                             help_text="Total transaction amount for this item")
    fees = models.DecimalField(max_digits=16, decimal_places=2, default=0,
                             help_text="Total fees for this item")
    payment_amount = models.DecimalField(max_digits=16, decimal_places=2, default=0,
                             help_text="Total payment amount for this item to transfer to vendor")
    # Some other fields

admin.py

class DealPaymentAdmin(ImportExportModelAdmin):
    readonly_fields=('product_type', 'payment_amount', 'fees', 'deal_status', 'deal', 'seller')
    exclude = ('object_id', )
    list_display = ('deal', 'seller', 'payment_amount', 'fees', 'rewards', 'fees_plan',
                'payment_status', 'deal_status', 'closing_date', 'date_modified')
    list_filter = ('payment_status',)
    fields = ('product_type', 'deal', 'seller', 'deal_status', 'payment_amount', 'fees', 'payment_status','payment_date')
    list_per_page = 30    

    def deal(self, obj):
        return     obj.product_type.model_class().objects.get(id=obj.object_id)

    def deal_status(self, obj):
        deal =     obj.product_type.model_class().objects.get(id=obj.object_id)
        if deal.publish_status and deal.active:
            return "Active"
        else:
            return "Closed"

    def closing_date(self, obj):
        # Need to sort by this 'closing_date' field. 
        # Both type of deals having 'closing_date' field.
        deal = obj.product_type.model_class().objects.get(id=obj.object_id)
        return deal.closing_date


    # Tried this.
    closing_date.admin_order_field = 'deal__closing_date'

I tried this admin_order_field from Django admin: how to sort by one of the custom list_display fields that has no database field but

But I get FieldError when tried sorting. I need to be able to sort by closing_date field in admin list display.

Thanks in advance.