我们如何在GORM/Golang中创建一个类似于Django field.choices的模型字段类型?

huangapple go评论81阅读模式
英文:

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"` 
    ....
}

huangapple
  • 本文由 发表于 2022年5月10日 02:25:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/72176627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定