问题描述
我试图在 Django 中使用枚举类型,但我觉得我没有做正确的事情......
我正在构建一个类似 ebay 的网络应用程序,其中我的列表保存在具有 .category
属性的数据库中。
class Listing(models.Model):
class Category(models.TextChoices):
TOY = "TO",_("Toys")
FASHION = "FA",_("Fashion")
ELECTRONICS = "EL",_("Electronics")
HOME = "HO",_("Home")
OTHERS = "OT",_("Others")
title = models.CharField(max_length=64)
category = models.CharField(
max_length=2,choices=Category.choices,default=Category.OTHERS,)
我提到了 Django's documentation 以使用枚举类型,但就我的理解而言,存在一些灰色区域。
当我渲染模板以显示 Listing
时,如何传递与我的 .category
的 Listing
关联的字符串值?
我尝试过这样的事情:
return render(request,"auctions/listing.html",{
"listing": listing,"category": Listing.Category[listing.category].label,})
或者我可以通过 "listing"
变量访问它吗?我希望浏览器为带有 Home
的 listing
显示 listing.category = "HO"
。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)