Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使HTML自定义字段在django admin中可排序_Django_Django Admin - Fatal编程技术网

使HTML自定义字段在django admin中可排序

使HTML自定义字段在django admin中可排序,django,django-admin,Django,Django Admin,我有一个非常简单的模型,它只包含一个名称和序列号。我可以使用该序列号询问API的状态,并希望将结果显示为图标/HTML: class ProductAdminForm(admin.ModelAdmin): class Meta: model = Product fields = ["get_status", "name",] def get_status(self, obj): status

我有一个非常简单的模型,它只包含一个名称和序列号。我可以使用该序列号询问API的状态,并希望将结果显示为图标/HTML:

class ProductAdminForm(admin.ModelAdmin):
    class Meta:
        model = Product
        fields = ["get_status", "name",]

    def get_status(self, obj):
        status = get_status_from_API(obj)["status"]
        style = """style="height: 10px; width: 10px; border-radius: 50%; COLOR display: inline-block;" """
    
        if status == 2:
            new_style = style.replace("COLOR", "background-color: green;")
        elif status == 1:
            new_style = style.replace("COLOR", "background-color: red;")
        else:
            new_style = style.replace("COLOR", "background-color: grey;")
        return mark_safe(f"""<span class="dot" {new_style}></span>""")
类ProductAdminForm(admin.ModelAdmin):
类元:
型号=产品
字段=[“获取_状态”、“名称”,]
def get_状态(自身、obj):
状态=从API(obj)[“状态”]
style=“”style=“高度:10px;宽度:10px;边界半径:50%;彩色显示:内联块;" """
如果状态==2:
新建样式=样式。替换(“颜色”,“背景色:绿色;”)
elif状态==1:
新样式=样式。替换(“颜色”,“背景色:红色;”)
其他:
新样式=样式。替换(“颜色”,“背景色:灰色;”)
返回标记为“安全(f”)

如何使
get\u status
列可排序?

您只能根据数据库中的属性进行排序

通常,list_显示的元素不是实际的数据库字段,不能用于排序(因为Django在数据库级别执行所有排序)

这意味着您不能根据API中对象的状态进行排序。但是,您可以通过设置
admin\u order\u field
对其他属性(如序列号)进行排序

如果您真的想按状态排序,您需要以某种方式将此状态存储在数据库中

一种解决方案是定期调用管理命令,获取所有对象的状态并将结果存储在数据库中

这样就可以根据对象的状态对其进行排序(和过滤)

将API结果存储在数据库中还有一个好处,即在管理员界面中查看对象时不需要执行任何API调用。这在API发生故障/速度慢时特别有用。明显的缺点是,根据调用update命令的频率,结果可能会稍微过时