Field gives a Django Ninja schema field more control than an ordinary Python type hint. It can supply a default value, change the external field name, or describe how filtering should translate into a Django QuerySet lookup. section 11.5 section 11.2.3
Common uses include:
- Set an optional filter’s default with Field(None). section 11.2.3
- Map a friendly API name to an internal Django relationship, such as rooms to room_set. section 11.2.4
- Map a query parameter to a lookup such as name__istartswith instead of using an exact match. section 11.2.3
Filtering venues
class VenueFilter(FilterSchema): name: Optional[str] = Field(None, q=["name__istartswith"]) The endpoint receives the filter schema through Query(...), then calls filters.filter(venues). A request containing name applies a starts-with lookup to the Venue queryset; an omitted name leaves the filter optional. section 11.2.3
Listing 11.11 Nesting Room data inside serialized Venue objects
# RiffMates/bands/api.py
...
from bands.models import Venue, Room #1
...
class RoomSchema(ModelSchema): #2
class Meta:
model = Room
fields = ["id", "name"]
class VenueOut(ModelSchema):
slug: str
url: str
rooms: list[RoomSchema] = Field(...,
alias="room_set") #3
...
Inspect the nested-schema example: rooms is exposed as a friendly API field while alias="room_set" connects it to Django’s related-object manager. section 11.2.4
