简体   繁体   中英

Django readonly_fields not showing data

My Orders model has a rate and total_amount field. I had to derive the rate from the different models so I created unit_rate .

Similarly, I wanted my total_amount fields to be a multiplication of quantity and unit_rate , which I tried by doing total_pay .

Here is my code:

class OrderAdmin(admin.ModelAdmin):

    def unit_rate(self,obj):
        self.rate = Product.objects.get(pk=obj.order_id)
        return self.rate.price

    def total_pay(self,obj):
        self.rate = Product.objects.get(pk=obj.order_id)
        self.total_amount = self.rate.price * obj.quantity
        return self.total_amount

    list_display = ('order_id', 'order_item', 'order_status', 'delivery_address', 'customer',
        'quantity','unit_rate','total_pay')

    readonly_fields = ('total_pay','unite_rate')

admin.site.register(Orders,OrderAdmin)

As total_pay and unit_rate are obtained from other columns, the admin doesn't need to enter them. That's why I kept them on readonly_fields .

The problem is that, whenever it creates an order through the admin interface, total_pay and unit_rate do not show up in the admin. It just shows a dash like this: - .

It has been doing this for a while, so I could really use your help. Thanks.

Actually digging little bit more for hours i found the solution.

class OrderAdmin(admin.ModelAdmin):

    list_display = ('order_id', 'order_item', 'order_status', 'delivery_address', 'customer',
        'quantity','unit_rate','total_pay')

    def unit_rate(self,obj):
        rate = Product.objects.get(pk=obj.order_item.product_id)
        return rate.price

    def total_pay(self,obj):
        rate = Product.objects.get(pk=obj.order_item.product_id)
        total_amount = rate.price * obj.quantity
        return total_amount

admin.site.register(Orders,OrderAdmin)

Actually i did not know how to pass product_id along with order_item . and i think even documentation is also does not help much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM