我有一个模型,我使用枚举进行选择:
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)
当管理站点呈现对象时,它不允许我保存它?有人遇到过类似的问题吗?
最佳答案
根据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.
name
和 value
应该相反,如下所示:
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/