or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

admin-extensions.mdindex.mdmanagement-commands.mdmodel-base-classes.mdmodel-fields.mdtemplate-tags.mdvalidators.md

model-fields.mddocs/

0

# Model Fields

1

2

Django Extensions provides custom model fields that extend Django's field types with specialized functionality including auto-generated slugs, timestamps, UUIDs, and JSON data handling. These fields are designed to handle common patterns in Django applications with minimal configuration.

3

4

## Capabilities

5

6

### AutoSlugField

7

8

Automatically generates slugs from other model fields with extensive customization options.

9

10

```python { .api }

11

class AutoSlugField(SlugField):

12

def __init__(

13

self,

14

populate_from=None,

15

separator='-',

16

overwrite=False,

17

overwrite_on_add=True,

18

allow_duplicates=False,

19

slugify_function=None,

20

max_unique_query_attempts=100,

21

**kwargs

22

):

23

"""

24

AutoSlugField that automatically populates from other fields.

25

26

Parameters:

27

- populate_from: Field name, list of fields, or callable to populate from

28

- separator: String used to separate slug components (default: '-')

29

- overwrite: If True, regenerate slug on every save (default: False)

30

- overwrite_on_add: If True, generate slug when adding new instances (default: True)

31

- allow_duplicates: If True, allow duplicate slugs (default: False)

32

- slugify_function: Custom function for slugification (default: django.template.defaultfilters.slugify)

33

- max_unique_query_attempts: Maximum attempts to find unique slug (default: 100)

34

"""

35

```

36

37

Usage examples:

38

39

```python

40

from django.db import models

41

from django_extensions.db.fields import AutoSlugField

42

43

class Article(models.Model):

44

title = models.CharField(max_length=200)

45

slug = AutoSlugField(populate_from='title')

46

47

class BlogPost(models.Model):

48

title = models.CharField(max_length=200)

49

author = models.CharField(max_length=100)

50

# Populate from multiple fields

51

slug = AutoSlugField(populate_from=['title', 'author'], separator='_')

52

53

class CustomSlugModel(models.Model):

54

name = models.CharField(max_length=100)

55

56

def custom_slugify(self, content):

57

return content.replace(' ', '_').lower()

58

59

slug = AutoSlugField(populate_from='name', slugify_function=custom_slugify)

60

```

61

62

### DateTime Fields

63

64

Automatic timestamp fields for tracking creation and modification times.

65

66

```python { .api }

67

class CreationDateTimeField(DateTimeField):

68

def __init__(self, **kwargs):

69

"""

70

DateTimeField that automatically sets creation datetime.

71

72

Sets editable=False, blank=True, auto_now_add=True by default.

73

Value is set once when object is first created.

74

"""

75

76

class ModificationDateTimeField(DateTimeField):

77

def __init__(self, **kwargs):

78

"""

79

DateTimeField that automatically updates modification datetime.

80

81

Sets editable=False, blank=True, auto_now=True by default.

82

Value is updated every time object is saved.

83

84

Respects the 'update_modified' attribute on model instances.

85

If update_modified=False, the field won't be updated on save.

86

"""

87

```

88

89

Usage examples:

90

91

```python

92

from django.db import models

93

from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField

94

95

class TimestampedModel(models.Model):

96

created = CreationDateTimeField()

97

modified = ModificationDateTimeField()

98

99

def save_without_timestamp_update(self, *args, **kwargs):

100

# Prevent modification timestamp from updating

101

self.update_modified = False

102

self.save(*args, **kwargs)

103

```

104

105

### RandomCharField

106

107

Generates random character strings with configurable character sets.

108

109

```python { .api }

110

class RandomCharField(CharField):

111

def __init__(

112

self,

113

length=None,

114

unique=False,

115

lowercase=False,

116

uppercase=False,

117

include_alpha=True,

118

include_digits=True,

119

include_punctuation=False,

120

keep_default=False,

121

max_unique_query_attempts=100,

122

**kwargs

123

):

124

"""

125

CharField that generates random character strings.

126

127

Parameters:

128

- length: Required. Length of random string to generate

129

- unique: If True, ensure uniqueness in database (default: False)

130

- lowercase: If True, force lowercase alpha characters (default: False)

131

- uppercase: If True, force uppercase alpha characters (default: False)

132

- include_alpha: Include alphabetic characters (default: True)

133

- include_digits: Include numeric digits (default: True)

134

- include_punctuation: Include punctuation characters (default: False)

135

- keep_default: Keep initial value if already set (default: False)

136

- max_unique_query_attempts: Max attempts to find unique value (default: 100)

137

138

Note: lowercase and uppercase are mutually exclusive

139

"""

140

```

141

142

Usage examples:

143

144

```python

145

from django.db import models

146

from django_extensions.db.fields import RandomCharField

147

148

class APIKey(models.Model):

149

key = RandomCharField(length=32, unique=True)

150

151

class Token(models.Model):

152

# Only uppercase letters and digits

153

token = RandomCharField(

154

length=16,

155

unique=True,

156

uppercase=True,

157

include_punctuation=False

158

)

159

160

class SessionID(models.Model):

161

# Include punctuation for stronger randomness

162

session_id = RandomCharField(

163

length=40,

164

unique=True,

165

include_punctuation=True

166

)

167

```

168

169

### UUID Fields

170

171

UUID field implementations with support for different UUID versions.

172

173

```python { .api }

174

class UUIDFieldMixin:

175

def __init__(

176

self,

177

auto=True,

178

version=4,

179

node=None,

180

clock_seq=None,

181

namespace=None,

182

uuid_name=None,

183

**kwargs

184

):

185

"""

186

Mixin for UUID field functionality.

187

188

Parameters:

189

- auto: Automatically generate UUID if not provided (default: True)

190

- version: UUID version (1, 3, 4, 5) - version 2 not supported (default: 4)

191

- node: Node value for UUID version 1

192

- clock_seq: Clock sequence for UUID version 1

193

- namespace: Namespace UUID for versions 3 and 5

194

- uuid_name: Name for versions 3 and 5 (defaults to field name)

195

"""

196

197

class ShortUUIDField(UUIDFieldMixin, CharField):

198

def __init__(self, **kwargs):

199

"""

200

Generates concise (22 characters), unambiguous, URL-safe UUIDs.

201

202

Requires 'shortuuid' package: pip install shortuuid

203

Uses base57 encoding to create shorter UUID representations.

204

"""

205

```

206

207

Usage examples:

208

209

```python

210

from django.db import models

211

from django_extensions.db.fields import ShortUUIDField

212

import uuid

213

214

class Document(models.Model):

215

# Standard UUID4 field (requires manual import)

216

id = models.UUIDField(primary_key=True, default=uuid.uuid4)

217

218

class ShortDocument(models.Model):

219

# Short UUID field (22 characters instead of 36)

220

id = ShortUUIDField(primary_key=True)

221

222

# For other UUID versions, you would typically use Django's built-in UUIDField

223

# with custom default functions

224

```

225

226

### JSONField

227

228

Field for storing and retrieving JSON data with automatic serialization.

229

230

```python { .api }

231

class JSONField(TextField):

232

def __init__(self, **kwargs):

233

"""

234

TextField that neatly serializes/deserializes JSON objects.

235

236

Automatically handles conversion between Python objects and JSON strings.

237

Uses DjangoJSONEncoder for serialization.

238

Default value is empty dict ({}).

239

240

Returns JSONDict for dict objects and JSONList for list objects

241

to ensure proper fixture serialization.

242

"""

243

244

class JSONDict(dict):

245

def __repr__(self):

246

"""Returns JSON representation for fixture compatibility."""

247

248

class JSONList(list):

249

def __repr__(self):

250

"""Returns JSON representation for fixture compatibility."""

251

```

252

253

Usage examples:

254

255

```python

256

from django.db import models

257

from django_extensions.db.fields.json import JSONField

258

259

class Configuration(models.Model):

260

name = models.CharField(max_length=100)

261

settings = JSONField() # Defaults to empty dict

262

263

def save(self, *args, **kwargs):

264

# Data is automatically serialized to JSON

265

if not self.settings:

266

self.settings = {'default': True}

267

super().save(*args, **kwargs)

268

269

# Usage

270

config = Configuration.objects.create(

271

name='app_config',

272

settings={

273

'debug': True,

274

'max_connections': 100,

275

'features': ['feature1', 'feature2']

276

}

277

)

278

279

# Retrieval - automatically deserialized

280

settings = config.settings # Python dict, not JSON string

281

debug_mode = settings['debug'] # True

282

```

283

284

## Field Inheritance and Customization

285

286

Django Extensions fields support all standard Django field options and can be customized further:

287

288

```python

289

from django.db import models

290

from django_extensions.db.fields import AutoSlugField, CreationDateTimeField

291

292

class CustomModel(models.Model):

293

title = models.CharField(max_length=200)

294

295

# AutoSlugField with custom options

296

slug = AutoSlugField(

297

populate_from='title',

298

max_length=100, # Limit slug length

299

help_text='Automatically generated from title',

300

overwrite=True, # Always regenerate on save

301

allow_duplicates=False

302

)

303

304

# CreationDateTimeField with custom options

305

created = CreationDateTimeField(

306

verbose_name='Date Created',

307

help_text='When this record was created'

308

)

309

310

class Meta:

311

ordering = ['-created']

312

```

313

314

## MongoDB Support

315

316

Django Extensions also provides MongoDB field equivalents:

317

318

```python

319

# Location: django_extensions.mongodb.fields

320

from django_extensions.mongodb.fields import (

321

AutoSlugField as MongoAutoSlugField,

322

CreationDateTimeField as MongoCreationDateTimeField,

323

ModificationDateTimeField as MongoModificationDateTimeField,

324

UUIDField as MongoUUIDField

325

)

326

```

327

328

## Common Patterns

329

330

```python

331

# Timestamped model with slug

332

class BlogPost(models.Model):

333

title = models.CharField(max_length=200)

334

slug = AutoSlugField(populate_from='title')

335

created = CreationDateTimeField()

336

modified = ModificationDateTimeField()

337

338

class Meta:

339

ordering = ['-created']

340

341

# API model with random key

342

class APIEndpoint(models.Model):

343

name = models.CharField(max_length=100)

344

api_key = RandomCharField(length=32, unique=True)

345

config = JSONField(default=dict)

346

created = CreationDateTimeField()

347

348

# User profile with short UUID

349

class UserProfile(models.Model):

350

id = ShortUUIDField(primary_key=True)

351

user = models.OneToOneField('auth.User', on_delete=models.CASCADE)

352

preferences = JSONField(default=dict)

353

slug = AutoSlugField(populate_from='user__username')

354

```