Django admin - sort by GenericForeignKey's field

ⅰ亾dé卋堺 提交于 2019-12-24 01:24:44

问题


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.

来源:https://stackoverflow.com/questions/34488496/django-admin-sort-by-genericforeignkeys-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!