Home > Blockchain >  How can we create a similar model field type to Django field.choices in GORM/Golang
How can we create a similar model field type to Django field.choices in GORM/Golang

Time:05-12

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.

CodePudding user response:

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