How to display a boolean property in the django admin

后端 未结 5 1412
说谎
说谎 2021-01-31 15:47

As we all know, displaying a method return value as boolean in the Django admin is easily done by setting the boolean attribute:

class MyMo         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-31 16:31

    You need to create a shadowing function to the property in the model. What I mean is that you will need to recreate a function in the ModelAdmin class with the same name as the property defined in the main Model.

    Example:

    # Model
    class Product(models.Model):
    
        @property  # you can omit this decorator if you will access this property as a method of the model instance
        def in_stock(self):
            # boolean check return
            return self.quantity > 0
    

    ...

    # Django-modeladmin
    class ProductAdmin(admin.ModelAdmin):
        list_display = ('in_stock', ...)
        def in_stock(self, instance):
            return instance.in_stock
    
        in_stock.boolean = True        
    

提交回复
热议问题