英文:
How can we create a similar model field type to Django field.choices in GORM/Golang
问题
我正在尝试创建一个结构字段,并将其值限制为一个值列表,例如:
state = ["locked", "unlocked"]
在Django模型中,我们使用字段选择器,例如:
class Book(models.Model):
LOCKED = 'LK'
UNLOCKED = 'UN'
STATE = [
('LK', 'Locked'),
('UL', 'Unlocked'),
]
book_state = models.CharField(choices=STATE, default=LOCKED)
我正在尝试使用Go中的gorm.model结构数据类型来复制上述内容。
英文:
I am trying to create a struct field, and limit its values to a list of values i.e,
state =["locked", "unlocked"]
now in Django models we use the field choices i.e
class Book(models.Model):
LOCKED = 'LK'
UNLOCKED = 'UN'
STATE = [
('LK', 'Locked'),
('UL', 'Unlocked'),
]
book_state = models.CharField(choices=STATE, default=LOCKED)
trying to replicate the above using a gorm.model struct data type in Go.
答案1
得分: 1
解决方案: 创建一个自定义的 Golang 类型,并将其添加为 GORM 模型字段
type BookState string
const (
Locked BookState = "locked"
Unlocked BookState = "unlocked"
)
然后创建你的 GORM 结构体模型字段
type Book struct {
Name string `json:"name" validate:"required"`
State BookState `json:"state" validate:"required"`
// ...
}
这样,你就可以在 GORM 模型中使用自定义的 BookState
类型作为字段了。
英文:
Solution: create a custom golang type with string and add it as gorm model field
type BookState string
const (
Locked BookState = "locked"
Unlocked BookState = "unlocked"
)
Then create your gorm struct model fields
type Book struct {
Name string `json:"name" validate:"required"`
State BookState `json:"state" validate: "required"`
....
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论