python - 使用 Enum 时 Admin 中的 Django 选择

标签 python django django-models django-admin django-orm

我有一个模型,我使用枚举进行选择:

class Agreement(models.Model):
    class Category(enum.Enum):
        EULA = 0
        PROVIDER = 1

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    category = models.IntegerField(
        choices=[(choice.name, choice.value)
                 for choice in Category])
    title = models.CharField(max_length=128)
    content = models.TextField()

我使用简单的管理站点注册来注册它:

admin.site.register(Agreement)

当管理站点呈现对象时,它不允许我保存它?有人遇到过类似的问题吗?

enter image description here

最佳答案

根据documentation :

The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name.

namevalue 应该相反,如下所示:

category = models.IntegerField(
    choices=[(choice.value, choice.name)
             for choice in Category])

因为category是一个整数字段,而name返回一个字符串。

关于python - 使用 Enum 时 Admin 中的 Django 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52359432/

相关文章:

javascript - 尝试访问 json 数据时未定义 (ajax)

javascript - 如何在 Python 中更新 Bokeh 的 JavaScript 回调中的源?

python fabric 运行 awk 命令返回 KeyError : 'print $1'

python - 检索 mptt 查询集的祖先查询集的高效函数

python - 即使使用 DJANGO 模型表单提交后,图片也不会在数据库中更新

django - Django 注解的数学运算

python - 如何查询当月的天数

python - 执行 docker exec 命令时 python 脚本的执行挂起

python - Django - 无法选择自定义日志记录处理程序类

Django:如何允许空值