QuerySetProxy
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.
Note
By default exposed QuerySet is already filtered to return only Models
related to parent Model
.
So if you issue post.categories.all()
you will get all categories related to that post, not all in table.
Note
Note that when accessing QuerySet API methods through QuerysetProxy you don't
need to use objects
attribute like in normal queries.
So note that it's post.categories.all()
and not post.categories.objects.all()
.
To learn more about available QuerySet methods visit queries
Warning
Querying related models from ManyToMany cleans list of related models loaded on parent model:
Example: post.categories.first()
will set post.categories to list of 1 related model -> the one returned by first()
Example 2: if post has 4 categories so len(post.categories) == 4
calling post.categories.limit(2).all()
-> will load only 2 children and now assert len(post.categories) == 2
This happens for all QuerysetProxy methods returning data: get
, all
and first
and in get_or_create
if model already exists.
Note that value returned by create
or created in get_or_create
and update_or_create
if model does not exist will be added to relation list (not clearing it).
Read data from database
get
get(**kwargs): -> Model
To grab just one of related models filtered by name you can use get(**kwargs)
method.
1 2 3 4 5 6 7 8 9 |
|
Tip
Read more in queries documentation get
get_or_create
get_or_create(_defaults: Optional[Dict[str, Any]] = None, **kwargs) -> Tuple[Model, bool]
Tries to get a row meeting the criteria and if NoMatch
exception is raised it creates a new one with given kwargs and _defaults.
Tip
Read more in queries documentation get_or_create
all
all(**kwargs) -> List[Optional["Model"]]
To get a list of related models use all()
method.
Note that you can filter the queryset, select related, exclude fields etc. like in normal query.
1 2 3 4 5 6 7 |
|
Tip
Read more in queries documentation all
iterate
iterate(**kwargs) -> AsyncGenerator["Model"]
To iterate on related models use iterate()
method.
Note that you can filter the queryset, select related, exclude fields etc. like in normal query.
1 2 3 |
|
Tip
Read more in queries documentation iterate
Insert/ update data into database
create
create(**kwargs): -> Model
Create related Model
directly from parent Model
.
The link table is automatically populated, as well as relation ids in the database.
1 2 3 4 |
|
Tip
Read more in queries documentation create
For ManyToMany
relations there is an additional functionality of passing parameters
that will be used to create a through model if you declared additional fields on explicitly
provided Through model.
Given sample like this:
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 |
|
You can populate fields on through model in the create()
call in a following way:
1 2 3 4 5 6 7 |
|
get_or_create
get_or_create(_defaults: Optional[Dict[str, Any]] = None, **kwargs) -> Tuple[Model, bool]
Tries to get a row meeting the criteria and if NoMatch exception is raised it creates a new one with given kwargs.
Tip
Read more in queries documentation get_or_create
update_or_create
update_or_create(**kwargs) -> Model
Updates the model, or in case there is no match in database creates a new one.
Tip
Read more in queries documentation update_or_create
update
update(**kwargs, each:bool = False) -> int
Updates the related model with provided keyword arguments, return number of updated rows.
Tip
Read more in queries documentation update
Note that for ManyToMany
relations update can also accept an argument with through field
name and a dictionary of fields.
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 |
|
In example above you can update attributes of postcategory
in a following call:
1 2 3 |
|
Filtering and sorting
filter
filter(*args, **kwargs) -> QuerySet
Allows you to filter by any Model attribute/field as well as to fetch instances, with a filter across an FK relationship.
Tip
Read more in queries documentation filter
exclude
exclude(*args, **kwargs) -> QuerySet
Works exactly the same as filter and all modifiers (suffixes) are the same, but returns a not condition.
Tip
Read more in queries documentation exclude
order_by
order_by(columns:Union[List, str]) -> QuerySet
With order_by() you can order the results from database based on your choice of fields.
Tip
Read more in queries documentation order_by
Joins and subqueries
select_related
select_related(related: Union[List, str]) -> QuerySet
Allows to prefetch related models during the same query.
With select_related always only one query is run against the database, meaning that one (sometimes complicated) join is generated and later nested models are processed in python.
Tip
Read more in queries documentation select_related
prefetch_related
prefetch_related(related: Union[List, str]) -> QuerySet
Allows to prefetch related models during query - but opposite to select_related each subsequent model is fetched in a separate database query.
With prefetch_related always one query per Model is run against the database, meaning that you will have multiple queries executed one after another.
Tip
Read more in queries documentation prefetch_related
Pagination and rows number
paginate
paginate(page: int, page_size: int = 20) -> QuerySet
Combines the offset and limit methods based on page number and size.
Tip
Read more in queries documentation paginate
limit
limit(limit_count: int) -> QuerySet
You can limit the results to desired number of parent models.
Tip
Read more in queries documentation limit
offset
offset(offset: int) -> QuerySet
You can offset the results by desired number of main models.
Tip
Read more in queries documentation offset
Selecting subset of columns
fields
fields(columns: Union[List, str, set, dict]) -> QuerySet
With fields() you can select subset of model columns to limit the data load.
Tip
Read more in queries documentation fields
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.
Tip
Read more in queries documentation exclude_fields
Aggregated functions
count
count(distinct: bool = True) -> int
Returns number of rows matching the given criteria (i.e. applied with filter and exclude)
Tip
Read more in queries documentation count
exists
exists() -> bool
Returns a bool value to confirm if there are rows matching the given criteria (applied with filter and exclude)
Tip
Read more in queries documentation exists