or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

database.mdexceptions.mdfunctions.mdindex.mdintegration.mdmodels.mdquerying.mdsignals.mdtransactions.mdvalidators.md

models.mddocs/

0

# Model Definition and Fields

1

2

Model classes and field types for defining database schemas in Tortoise ORM. Models inherit from the base Model class and use field instances to define database columns with proper typing, validation, and relationships.

3

4

## Capabilities

5

6

### Model Base Class

7

8

Base class that all ORM models inherit from, providing database operations, field management, and relationship handling.

9

10

```python { .api }

11

class Model:

12

"""Base model class for database entities."""

13

14

def __init__(self, **kwargs):

15

"""

16

Initialize model instance with field values.

17

18

Args:

19

**kwargs: Field values as keyword arguments

20

"""

21

22

async def save(self):

23

"""

24

Save model instance to database (insert or update).

25

26

Returns:

27

Model: The saved model instance

28

"""

29

30

async def delete(self):

31

"""

32

Delete model instance from database.

33

34

Returns:

35

None

36

"""

37

38

async def refresh_from_db(self, fields=None):

39

"""

40

Refresh model instance from database.

41

42

Args:

43

fields (list, optional): Specific fields to refresh

44

"""

45

46

@classmethod

47

async def create(cls, **kwargs):

48

"""

49

Create and save new model instance.

50

51

Args:

52

**kwargs: Field values for the new instance

53

54

Returns:

55

Model: The created model instance

56

"""

57

58

@classmethod

59

async def get(cls, **kwargs):

60

"""

61

Get single model instance matching criteria.

62

63

Args:

64

**kwargs: Filter criteria

65

66

Returns:

67

Model: The matching model instance

68

69

Raises:

70

DoesNotExist: If no matching instance found

71

"""

72

73

@classmethod

74

async def get_or_none(cls, **kwargs):

75

"""

76

Get single model instance or None if not found.

77

78

Args:

79

**kwargs: Filter criteria

80

81

Returns:

82

Model or None: The matching model instance or None

83

"""

84

85

@classmethod

86

def all(cls):

87

"""

88

Get QuerySet for all instances of this model.

89

90

Returns:

91

QuerySet: QuerySet for all instances

92

"""

93

94

@classmethod

95

def filter(cls, **kwargs):

96

"""

97

Get filtered QuerySet.

98

99

Args:

100

**kwargs: Filter criteria

101

102

Returns:

103

QuerySet: Filtered QuerySet

104

"""

105

106

@classmethod

107

def exclude(cls, **kwargs):

108

"""

109

Get QuerySet excluding matching instances.

110

111

Args:

112

**kwargs: Exclusion criteria

113

114

Returns:

115

QuerySet: Filtered QuerySet

116

"""

117

118

@classmethod

119

def describe(cls, serializable=True):

120

"""

121

Describe model schema.

122

123

Args:

124

serializable (bool): Return JSON-serializable format

125

126

Returns:

127

dict: Model description

128

"""

129

130

class Meta:

131

"""Model metadata configuration."""

132

table = None # Custom table name

133

app = None # App label

134

abstract = False # Abstract model flag

135

unique_together = () # Unique constraint tuples

136

ordering = () # Default ordering

137

```

138

139

### Data Fields

140

141

Field types for storing different kinds of data with validation and database mapping.

142

143

#### Numeric Fields

144

145

```python { .api }

146

class IntField:

147

"""Integer field."""

148

def __init__(self, pk=False, unique=False, index=False, default=None, null=False, **kwargs): ...

149

150

class BigIntField:

151

"""Big integer field for large numbers."""

152

def __init__(self, pk=False, unique=False, index=False, default=None, null=False, **kwargs): ...

153

154

class SmallIntField:

155

"""Small integer field for small numbers."""

156

def __init__(self, pk=False, unique=False, index=False, default=None, null=False, **kwargs): ...

157

158

class FloatField:

159

"""Floating point number field."""

160

def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...

161

162

class DecimalField:

163

"""Decimal field for precise decimal numbers."""

164

def __init__(self, max_digits, decimal_places, unique=False, index=False, default=None, null=False, **kwargs): ...

165

```

166

167

#### Text Fields

168

169

```python { .api }

170

class CharField:

171

"""Character field with maximum length."""

172

def __init__(self, max_length, unique=False, index=False, default=None, null=False, **kwargs): ...

173

174

class TextField:

175

"""Large text field for long text content."""

176

def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...

177

178

class UUIDField:

179

"""UUID field for storing UUID values."""

180

def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...

181

```

182

183

#### Date and Time Fields

184

185

```python { .api }

186

class DateField:

187

"""Date field for storing dates."""

188

def __init__(self, unique=False, index=False, default=None, null=False, auto_now=False, auto_now_add=False, **kwargs): ...

189

190

class DatetimeField:

191

"""Datetime field for storing date and time."""

192

def __init__(self, unique=False, index=False, default=None, null=False, auto_now=False, auto_now_add=False, **kwargs): ...

193

194

class TimeField:

195

"""Time field for storing time values."""

196

def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...

197

198

class TimeDeltaField:

199

"""Time delta field for storing time differences."""

200

def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...

201

```

202

203

#### Other Data Fields

204

205

```python { .api }

206

class BooleanField:

207

"""Boolean field for true/false values."""

208

def __init__(self, default=None, null=False, **kwargs): ...

209

210

class BinaryField:

211

"""Binary field for storing binary data."""

212

def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...

213

214

class JSONField:

215

"""JSON field for storing JSON data."""

216

def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...

217

```

218

219

#### Enum Fields

220

221

```python { .api }

222

class IntEnumField:

223

"""Integer enumeration field."""

224

def __init__(self, enum_type, unique=False, index=False, default=None, null=False, **kwargs): ...

225

226

class CharEnumField:

227

"""Character enumeration field."""

228

def __init__(self, enum_type, max_length=None, unique=False, index=False, default=None, null=False, **kwargs): ...

229

```

230

231

### Relational Fields

232

233

Fields for defining relationships between models.

234

235

#### Foreign Key Relationships

236

237

```python { .api }

238

class ForeignKeyField:

239

"""Foreign key field for many-to-one relationships."""

240

def __init__(self, model_name, related_name=None, on_delete="CASCADE", to_field=None, **kwargs):

241

"""

242

Args:

243

model_name (str): Related model in "app.Model" format

244

related_name (str, optional): Name for reverse relation

245

on_delete (str): Deletion behavior ("CASCADE", "RESTRICT", "SET_NULL", "SET_DEFAULT", "NO_ACTION")

246

to_field (str, optional): Field to reference (defaults to pk)

247

"""

248

```

249

250

#### One-to-One Relationships

251

252

```python { .api }

253

class OneToOneField:

254

"""One-to-one field for one-to-one relationships."""

255

def __init__(self, model_name, related_name=None, on_delete="CASCADE", to_field=None, **kwargs):

256

"""

257

Args:

258

model_name (str): Related model in "app.Model" format

259

related_name (str, optional): Name for reverse relation

260

on_delete (str): Deletion behavior

261

to_field (str, optional): Field to reference (defaults to pk)

262

"""

263

```

264

265

#### Many-to-Many Relationships

266

267

```python { .api }

268

class ManyToManyField:

269

"""Many-to-many field for many-to-many relationships."""

270

def __init__(self, model_name, related_name=None, through=None, forward_key=None, backward_key=None, **kwargs):

271

"""

272

Args:

273

model_name (str): Related model in "app.Model" format

274

related_name (str, optional): Name for reverse relation

275

through (str, optional): Through table name

276

forward_key (str, optional): Forward foreign key name

277

backward_key (str, optional): Backward foreign key name

278

"""

279

```

280

281

#### Relation Descriptor Classes

282

283

Classes for handling reverse relationship access and nullable relations.

284

285

```python { .api }

286

class ForeignKeyRelation:

287

"""Descriptor for accessing foreign key related objects."""

288

289

class ForeignKeyNullableRelation:

290

"""Descriptor for accessing nullable foreign key related objects."""

291

292

class OneToOneRelation:

293

"""Descriptor for accessing one-to-one related objects."""

294

295

class OneToOneNullableRelation:

296

"""Descriptor for accessing nullable one-to-one related objects."""

297

298

class ManyToManyRelation:

299

"""Descriptor for accessing many-to-many related objects."""

300

301

class BackwardFKRelation:

302

"""Descriptor for reverse foreign key relationships."""

303

304

class BackwardOneToOneRelation:

305

"""Descriptor for reverse one-to-one relationships."""

306

307

class ReverseRelation:

308

"""Base class for reverse relationship descriptors."""

309

```

310

311

### Field Options and Constraints

312

313

Common field options available for all field types.

314

315

#### OnDelete Constants

316

317

```python { .api }

318

CASCADE = "CASCADE" # Delete related objects

319

RESTRICT = "RESTRICT" # Prevent deletion if related objects exist

320

SET_NULL = "SET_NULL" # Set foreign key to NULL

321

SET_DEFAULT = "SET_DEFAULT" # Set foreign key to default value

322

NO_ACTION = "NO_ACTION" # No action taken

323

324

class OnDelete:

325

"""Enumeration of deletion behavior constants."""

326

CASCADE = "CASCADE"

327

RESTRICT = "RESTRICT"

328

SET_NULL = "SET_NULL"

329

SET_DEFAULT = "SET_DEFAULT"

330

NO_ACTION = "NO_ACTION"

331

```

332

333

#### Field Base Class

334

335

```python { .api }

336

class Field:

337

"""Base class for all field types."""

338

def __init__(self,

339

pk=False, # Primary key flag

340

unique=False, # Unique constraint

341

index=False, # Database index

342

default=None, # Default value

343

null=False, # Allow NULL values

344

description=None, # Field description

345

**kwargs): ...

346

```

347

348

## Usage Examples

349

350

### Basic Model Definition

351

352

```python

353

from tortoise.models import Model

354

from tortoise import fields

355

356

class User(Model):

357

id = fields.IntField(pk=True)

358

username = fields.CharField(max_length=20, unique=True)

359

email = fields.CharField(max_length=100, index=True)

360

full_name = fields.CharField(max_length=50, null=True)

361

created_at = fields.DatetimeField(auto_now_add=True)

362

updated_at = fields.DatetimeField(auto_now=True)

363

is_active = fields.BooleanField(default=True)

364

profile_data = fields.JSONField(default=dict)

365

366

class Meta:

367

table = "users"

368

ordering = ["-created_at"]

369

370

class Post(Model):

371

id = fields.IntField(pk=True)

372

title = fields.CharField(max_length=200)

373

content = fields.TextField()

374

author = fields.ForeignKeyField("models.User", related_name="posts")

375

created_at = fields.DatetimeField(auto_now_add=True)

376

tags = fields.ManyToManyField("models.Tag", related_name="posts")

377

378

class Meta:

379

table = "posts"

380

381

class Tag(Model):

382

id = fields.IntField(pk=True)

383

name = fields.CharField(max_length=50, unique=True)

384

385

class Meta:

386

table = "tags"

387

```

388

389

### Model Operations

390

391

```python

392

# Create instances

393

user = await User.create(

394

username="alice",

395

email="alice@example.com",

396

full_name="Alice Smith"

397

)

398

399

post = await Post.create(

400

title="My First Post",

401

content="Hello world!",

402

author=user

403

)

404

405

# Get instances

406

user = await User.get(username="alice")

407

post = await Post.get(id=1)

408

409

# Update instances

410

user.full_name = "Alice Johnson"

411

await user.save()

412

413

# Delete instances

414

await post.delete()

415

```

416

417

### Relationships

418

419

```python

420

# Access foreign key relationships

421

post = await Post.get(id=1)

422

author = await post.author # Load related user

423

424

# Access reverse foreign key relationships

425

user = await User.get(id=1)

426

user_posts = await user.posts.all() # Get all posts by user

427

428

# Many-to-many relationships

429

tag = await Tag.create(name="python")

430

await post.tags.add(tag) # Add tag to post

431

post_tags = await post.tags.all() # Get all tags for post

432

```