Excluding from nested models#
The exclude option can be used to exclude fields from models that are related to our data model by using dotted
paths. For example, exclude={"a.b"} would exclude the b attribute of an instance nested on the a attribute.
To demonstrate, let’s adjust our script to add an Address model, that is related to the Person model:
1from __future__ import annotations
2
3from dataclasses import dataclass
4
5from litestar import Litestar, get
6from litestar.dto import DataclassDTO, DTOConfig
7from litestar.params import FromPath
8
9
10@dataclass
11class Address:
12 street: str
13 city: str
14 country: str
15
16
17@dataclass
18class Person:
19 name: str
20 age: int
21 email: str
22 address: Address
23
24
25class ReadDTO(DataclassDTO[Person]):
26 config = DTOConfig(exclude={"email", "address.street"})
27
28
29@get("/person/{name:str}", return_dto=ReadDTO, sync_to_thread=False)
30def get_person(name: FromPath[str]) -> Person:
31 # Your logic to retrieve the person goes here
32 # For demonstration purposes, a placeholder Person instance is returned
33 address = Address(street="123 Main St", city="Cityville", country="Countryland")
34 return Person(name=name, age=30, email=f"email_of_{name}@example.com", address=address)
35
36
37app = Litestar(route_handlers=[get_person])
The Address model has three attributes, street, city, and country, and we’ve added an address
attribute to the Person model.
The ReadDTO class has been updated to exclude the street attribute of the nested Address model using the
dotted path syntax "address.street".
Inside the handler, we create an Address instance and assign it to the address attribute of the Person.
When we call our handler, we can see that the street attribute is not included in the response: