Selecting subset of columns
To select only chosen columns of your model you can use following functions.
fields(columns: Union[list, str, set, dict]) -> QuerySetexclude_fields(columns: Union[list, str, set, dict]) -> QuerySet-
flatten_fields(columns: Union[list, str, set, tuple, dict, FieldAccessor]) -> QuerySet -
QuerysetProxyQuerysetProxy.fields(columns: Union[list, str, set, dict])methodQuerysetProxy.exclude_fields(columns: Union[list, str, set, dict])method
fields
fields(columns: Union[list, str, set, dict]) -> QuerySet
With fields() you can select subset of model columns to limit the data load.
Note
Note that fields() and exclude_fields() works both for main models (on
normal queries like get, all etc.)
as well as select_related and prefetch_related models (with nested notation).
Given a sample data like following:
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
You can select specified fields by passing a str, list[str], set[str] or dict with
nested definition.
To include related models use
notation {related_name}__{column}[__{optional_next} etc.].
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
fields() can be called several times, building up the columns to select.
If you include related models into select_related() call but you won't specify columns
for those models in fields
- implies a list of all fields for those nested models.
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 | |
Warning
Mandatory fields cannot be excluded as it will raise ValidationError, to
exclude a field it has to be nullable.
The values() method can be used to exclude mandatory fields, though data will
be returned as a dict.
You cannot exclude mandatory model columns - manufacturer__name in this example.
| Python | |
|---|---|
1 2 3 4 5 6 7 | |
Tip
Pk column cannot be excluded - it's always auto added even if not explicitly included.
You can also pass fields to include as dictionary or set.
To mark a field as included in a dictionary use it's name as key and ellipsis as value.
To traverse nested models use nested dictionaries.
To include fields at last level instead of nested dictionary a set can be used.
To include whole nested model specify model related field name and ellipsis.
Below you can see examples that are equivalent:
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
Note
All methods that do not return the rows explicitly returns a QuerySet instance so you can chain them together
So operations like filter(), select_related(), limit() and offset() etc. can be chained.
Something like Track.objects.select_related("album").filter(album__name="Malibu").offset(1).limit(1).all()
exclude_fields
exclude_fields(columns: Union[list, str, set, dict]) -> QuerySet
With exclude_fields() you can select subset of model columns that will be excluded to
limit the data load.
It's the opposite of fields() method so check documentation above to see what options
are available.
Especially check above how you can pass also nested dictionaries and sets as a mask to exclude fields from whole hierarchy.
Note
Note that fields() and exclude_fields() works both for main models (on
normal queries like get, all etc.)
as well as select_related and prefetch_related models (with nested notation).
Below you can find few simple examples:
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | |
Warning
Mandatory fields cannot be excluded as it will raise ValidationError, to
exclude a field it has to be nullable.
The values() method can be used to exclude mandatory fields, though data will
be returned as a dict.
Tip
Pk column cannot be excluded - it's always auto added even if explicitly excluded.
Note
All methods that do not return the rows explicitly returns a QuerySet instance so you can chain them together
So operations like filter(), select_related(), limit() and offset() etc. can be chained.
Something like Track.object.select_related("album").filter(album__name="Malibu").offset(1).limit(1).all()
flatten_fields
flatten_fields(columns: Union[list, str, set, tuple, dict, FieldAccessor]) -> QuerySet
With flatten_fields() you can render selected related models as their primary
key value on model_dump() instead of the default nested dict. This is useful
when your API clients expect {"manufacturer": 1} rather than
{"manufacturer": {"id": 1, "name": "Toyota", ...}}.
Accepts the same input forms as fields() / exclude_fields() (string, list,
set, tuple, dict-with-Ellipsis) plus FieldAccessor / list of accessors.
Works across foreign keys, many-to-many, and reverse relations.
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 | |
The same can be written in nested-dict form:
| Python | |
|---|---|
1 | |
Or with a FieldAccessor:
| Python | |
|---|---|
1 | |
Deeply nested relations use __:
| Python | |
|---|---|
1 2 3 4 5 6 7 | |
Lists of pks for many-to-many and reverse relations:
| Python | |
|---|---|
1 2 | |
Note
Relations listed in flatten_fields() are auto-loaded — single-valued
foreign keys are added to select_related(), many-to-many and reverse
relations to prefetch_related(). You don't have to load them yourself.
flatten_all on model_dump
model.model_dump(flatten_all=True) collapses every related model at every depth
to its primary key in one shot. model.model_dump(flatten_fields=...) accepts
the same input forms as the queryset method and works even on models not loaded
via a queryset.
| Python | |
|---|---|
1 2 3 4 5 | |
Validation rules
Flatten directives conflict with sub-field selection on the flattened relation
— you can't attach children to a scalar pk. The following raise
QueryDefinitionError:
flatten_fields('manufacturer')combined withfields({'manufacturer': {'name'}})flatten_fields('manufacturer')combined withexclude_fields({'manufacturer': {'name'}})flatten_fields(['manufacturer', 'manufacturer__hq'])— the deeper path is unreachableflatten_fields('name')on a non-relation columnflatten_fields('manufacturer__nonexistent')— unknown relationmodel_dump(flatten_all=True, exclude_primary_keys=True)— directly contradictory
Whole-relation include/exclude (e.g. fields({'manufacturer'})) is fine
alongside a flatten directive.
Filtering through a flattened relation still works — the join is generated for the filter, and the rendered output is just the pk:
| Python | |
|---|---|
1 2 3 4 5 6 7 | |
QuerysetProxy methods
When access directly the related ManyToMany field as well as ReverseForeignKey
returns the list of related models.
But at the same time it exposes subset of QuerySet API, so you can filter, create, select related etc related models directly from parent model.
fields
Works exactly the same as fields function above but allows you to select columns from related objects from other side of the relation.
Tip
To read more about QuerysetProxy visit querysetproxy section
exclude_fields
Works exactly the same as exclude_fields function above but allows you to select columns from related objects from other side of the relation.
Tip
To read more about QuerysetProxy visit querysetproxy section
flatten_fields
Works exactly the same as flatten_fields function above but applied to the related-side queryset.
Tip
To read more about QuerysetProxy visit querysetproxy section