You can define default values for struct fields using the gorm:"default:value" tag. These values are used by the database when the field is a Go zero-value (e.g., 0, '', false).
Handling Zero-Values
Because GORM treats zero-values as 'empty', it won't send them to the database, which triggers the default tag. If you actually want to save a zero-value (like 0 or false) instead of the default, use a pointer type (e.g., *int) or a sql.Null* type.
Database Functions and Generated Columns
- To use a database function as a default (e.g.,
uuid_generate_v3()), use the default tag with the function call. - If you want to skip defining a default value during GORM migrations for a field that has a database-level default or virtual/generated value, use
default:(-). - For virtual/generated columns, you may need to disable create/update permissions using Field-Level Permission.
SQLite Limitation
SQLite does not support default values during batch inserts. If you attempt a batch insert where some records rely on a default tag, it will fail. A workaround is to manually assign the default value within a BeforeCreate hook.
type User struct {
ID string `gorm:"default:uuid_generate_v3()"` // database function
FirstName string
LastName string
Age uint8
// Generated column: skip migration definition with default:(-)
FullName string `gorm:"->;type:GENERATED ALWAYS AS (concat(firstname,' ',lastname));default:(-);"`
}
// Workaround for SQLite batch insert default values
func (p *Pet) BeforeCreate(tx *gorm.DB) (err error) {
if p.Name == "" {
p.Name = "cat"
}
return nil
}