# relations.querysetproxy
## QuerysetProxy Objects
```python
class QuerysetProxy(Generic[T])
```
Exposes QuerySet methods on relations, but also handles creating and removing
of through Models for m2m relations.
#### queryset
```python
| @property
| queryset() -> "QuerySet[T]"
```
Returns queryset if it's set, AttributeError otherwise.
**Returns**:
`QuerySet`: QuerySet
#### queryset
```python
| @queryset.setter
| queryset(value: "QuerySet") -> None
```
Set's the queryset. Initialized in RelationProxy.
**Arguments**:
- `value` (`QuerySet`): QuerySet
#### \_assign\_child\_to\_parent
```python
| _assign_child_to_parent(child: Optional["T"]) -> None
```
Registers child in parents RelationManager.
**Arguments**:
- `child` (`Model`): child to register on parent side.
#### \_register\_related
```python
| _register_related(child: Union["T", Sequence[Optional["T"]]]) -> None
```
Registers child/ children in parents RelationManager.
**Arguments**:
- `child` (`Union[Model,List[Model]]`): child or list of children models to register.
#### \_clean\_items\_on\_load
```python
| _clean_items_on_load() -> None
```
Cleans the current list of the related models.
#### create\_through\_instance
```python
| async create_through_instance(child: "T", **kwargs: Any) -> None
```
Crete a through model instance in the database for m2m relations.
**Arguments**:
- `kwargs` (`Any`): dict of additional keyword arguments for through instance
- `child` (`Model`): child model instance
#### update\_through\_instance
```python
| async update_through_instance(child: "T", **kwargs: Any) -> None
```
Updates a through model instance in the database for m2m relations.
**Arguments**:
- `kwargs` (`Any`): dict of additional keyword arguments for through instance
- `child` (`Model`): child model instance
#### upsert\_through\_instance
```python
| async upsert_through_instance(child: "T", **kwargs: Any) -> None
```
Updates a through model instance in the database for m2m relations if
it already exists, else creates one.
**Arguments**:
- `kwargs` (`Any`): dict of additional keyword arguments for through instance
- `child` (`Model`): child model instance
#### delete\_through\_instance
```python
| async delete_through_instance(child: "T") -> None
```
Removes through model instance from the database for m2m relations.
**Arguments**:
- `child` (`Model`): child model instance
#### exists
```python
| async exists() -> bool
```
Returns a bool value to confirm if there are rows matching the given criteria
(applied with `filter` and `exclude` if set).
Actual call delegated to QuerySet.
**Returns**:
`bool`: result of the check
#### count
```python
| async count() -> int
```
Returns number of rows matching the given criteria
(applied with `filter` and `exclude` if set before).
Actual call delegated to QuerySet.
**Returns**:
`int`: number of rows
#### max
```python
| async max(columns: Union[str, List[str]]) -> Any
```
Returns max value of columns for rows matching the given criteria
(applied with `filter` and `exclude` if set before).
**Returns**:
`Any`: max value of column(s)
#### min
```python
| async min(columns: Union[str, List[str]]) -> Any
```
Returns min value of columns for rows matching the given criteria
(applied with `filter` and `exclude` if set before).
**Returns**:
`Any`: min value of column(s)
#### sum
```python
| async sum(columns: Union[str, List[str]]) -> Any
```
Returns sum value of columns for rows matching the given criteria
(applied with `filter` and `exclude` if set before).
**Returns**:
`int`: sum value of columns
#### avg
```python
| async avg(columns: Union[str, List[str]]) -> Any
```
Returns avg value of columns for rows matching the given criteria
(applied with `filter` and `exclude` if set before).
**Returns**:
`Union[int, float, List]`: avg value of columns
#### clear
```python
| async clear(keep_reversed: bool = True) -> int
```
Removes all related models from given relation.
Removes all through models for m2m relation.
For reverse FK relations keep_reversed flag marks if the reversed models
should be kept or deleted from the database too (False means that models
will be deleted, and not only removed from relation).
**Arguments**:
or not, keep_reversed=False deletes them from database.
- `keep_reversed` (`bool`): flag if reverse models in reverse FK should be deleted
**Returns**:
`int`: number of deleted models
#### first
```python
| async first(*args: Any, **kwargs: Any) -> "T"
```
Gets the first row from the db ordered by primary key column ascending.
Actual call delegated to QuerySet.
Passing args and/or kwargs is a shortcut and equals to calling
`filter(*args, **kwargs).first()`.
List of related models is cleared before the call.
**Arguments**:
- `kwargs`:
**Returns**:
`_asyncio.Future`:
#### get\_or\_none
```python
| async get_or_none(*args: Any, **kwargs: Any) -> Optional["T"]
```
Get's the first row from the db meeting the criteria set by kwargs.
If no criteria set it will return the last row in db sorted by pk.
Passing args and/or kwargs is a shortcut and equals to calling
`filter(*args, **kwargs).get_or_none()`.
If not match is found None will be returned.
**Arguments**:
- `kwargs` (`Any`): fields names and proper value types
**Returns**:
`Model`: returned model
#### get
```python
| async get(*args: Any, **kwargs: Any) -> "T"
```
Get's the first row from the db meeting the criteria set by kwargs.
If no criteria set it will return the last row in db sorted by pk.
Passing args and/or kwargs is a shortcut and equals to calling
`filter(*args, **kwargs).get()`.
Actual call delegated to QuerySet.
List of related models is cleared before the call.
**Raises**:
- `NoMatch`: if no rows are returned
- `MultipleMatches`: if more than 1 row is returned.
**Arguments**:
- `kwargs` (`Any`): fields names and proper value types
**Returns**:
`Model`: returned model
#### all
```python
| async all(*args: Any, **kwargs: Any) -> List["T"]
```
Returns all rows from a database for given model for set filter options.
Passing args and/or kwargs is a shortcut and equals to calling
`filter(*args, **kwargs).all()`.
If there are no rows meeting the criteria an empty list is returned.
Actual call delegated to QuerySet.
List of related models is cleared before the call.
**Arguments**:
- `kwargs` (`Any`): fields names and proper value types
**Returns**:
`List[Model]`: list of returned models
#### create
```python
| async create(**kwargs: Any) -> "T"
```
Creates the model instance, saves it in a database and returns the updates model
(with pk populated if not passed and autoincrement is set).
The allowed kwargs are `Model` fields names and proper value types.
For m2m relation the through model is created automatically.
Actual call delegated to QuerySet.
**Arguments**:
- `kwargs` (`Any`): fields names and proper value types
**Returns**:
`Model`: created model
#### update
```python
| async update(each: bool = False, **kwargs: Any) -> int
```
Updates the model table after applying the filters from kwargs.
You have to either pass a filter to narrow down a query or explicitly pass
each=True flag to affect whole table.
**Arguments**:
- `each` (`bool`): flag if whole table should be affected if no filter is passed
- `kwargs` (`Any`): fields names and proper value types
**Returns**:
`int`: number of updated rows
#### get\_or\_create
```python
| async get_or_create(*args: Any, **kwargs: Any) -> "T"
```
Combination of create and get methods.
Tries to get a row meeting the criteria fro kwargs
and if `NoMatch` exception is raised
it creates a new one with given kwargs.
**Arguments**:
- `kwargs` (`Any`): fields names and proper value types
**Returns**:
`Model`: returned or created Model
#### update\_or\_create
```python
| async update_or_create(**kwargs: Any) -> "T"
```
Updates the model, or in case there is no match in database creates a new one.
Actual call delegated to QuerySet.
**Arguments**:
- `kwargs` (`Any`): fields names and proper value types
**Returns**:
`Model`: updated or created model
#### filter
```python
| filter(*args: Any, **kwargs: Any) -> "QuerysetProxy[T]"
```
Allows you to filter by any `Model` attribute/field
as well as to fetch instances, with a filter across an FK relationship.
You can use special filter suffix to change the filter operands:
* exact - like `album__name__exact='Malibu'` (exact match)
* iexact - like `album__name__iexact='malibu'` (exact match case insensitive)
* contains - like `album__name__contains='Mal'` (sql like)
* icontains - like `album__name__icontains='mal'` (sql like case insensitive)
* in - like `album__name__in=['Malibu', 'Barclay']` (sql in)
* isnull - like `album__name__isnull=True` (sql is null)
(isnotnull `album__name__isnull=False` (sql is not null))
* gt - like `position__gt=3` (sql >)
* gte - like `position__gte=3` (sql >=)
* lt - like `position__lt=3` (sql <)
* lte - like `position__lte=3` (sql <=)
* startswith - like `album__name__startswith='Mal'` (exact start match)
* istartswith - like `album__name__istartswith='mal'` (case insensitive)
* endswith - like `album__name__endswith='ibu'` (exact end match)
* iendswith - like `album__name__iendswith='IBU'` (case insensitive)
Actual call delegated to QuerySet.
**Arguments**:
- `kwargs` (`Any`): fields names and proper value types
**Returns**:
`QuerysetProxy`: filtered QuerysetProxy
#### exclude
```python
| exclude(*args: Any, **kwargs: Any) -> "QuerysetProxy[T]"
```
Works exactly the same as filter and all modifiers (suffixes) are the same,
but returns a *not* condition.
So if you use `filter(name='John')` which is `where name = 'John'` in SQL,
the `exclude(name='John')` equals to `where name <> 'John'`
Note that all conditions are joined so if you pass multiple values it
becomes a union of conditions.
`exclude(name='John', age>=35)` will become
`where not (name='John' and age>=35)`
Actual call delegated to QuerySet.
**Arguments**:
- `kwargs` (`Any`): fields names and proper value types
**Returns**:
`QuerysetProxy`: filtered QuerysetProxy
#### select\_all
```python
| select_all(follow: bool = False) -> "QuerysetProxy[T]"
```
By default adds only directly related models.
If follow=True is set it adds also related models of related models.
To not get stuck in an infinite loop as related models also keep a relation
to parent model visited models set is kept.
That way already visited models that are nested are loaded, but the load do not
follow them inside. So Model A -> Model B -> Model C -> Model A -> Model X
will load second Model A but will never follow into Model X.
Nested relations of those kind need to be loaded manually.
**Arguments**:
by default only directly related models are saved
with follow=True also related models of related models are saved
- `follow` (`bool`): flag to trigger deep save -
**Returns**:
`Model`: reloaded Model
#### select\_related
```python
| select_related(related: Union[List, str]) -> "QuerysetProxy[T]"
```
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.
To fetch related model use `ForeignKey` names.
To chain related `Models` relation use double underscores between names.
Actual call delegated to QuerySet.
**Arguments**:
- `related` (`Union[List, str]`): list of relation field names, can be linked by '__' to nest
**Returns**:
`QuerysetProxy`: QuerysetProxy
#### prefetch\_related
```python
| prefetch_related(related: Union[List, str]) -> "QuerysetProxy[T]"
```
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.
To fetch related model use `ForeignKey` names.
To chain related `Models` relation use double underscores between names.
Actual call delegated to QuerySet.
**Arguments**:
- `related` (`Union[List, str]`): list of relation field names, can be linked by '__' to nest
**Returns**:
`QuerysetProxy`: QuerysetProxy
#### paginate
```python
| paginate(page: int, page_size: int = 20) -> "QuerysetProxy[T]"
```
You can paginate the result which is a combination of offset and limit clauses.
Limit is set to page size and offset is set to (page-1) * page_size.
Actual call delegated to QuerySet.
**Arguments**:
- `page_size` (`int`): numbers of items per page
- `page` (`int`): page number
**Returns**:
`QuerySet`: QuerySet
#### limit
```python
| limit(limit_count: int) -> "QuerysetProxy[T]"
```
You can limit the results to desired number of parent models.
Actual call delegated to QuerySet.
**Arguments**:
- `limit_count` (`int`): number of models to limit
**Returns**:
`QuerysetProxy`: QuerysetProxy
#### offset
```python
| offset(offset: int) -> "QuerysetProxy[T]"
```
You can also offset the results by desired number of main models.
Actual call delegated to QuerySet.
**Arguments**:
- `offset` (`int`): numbers of models to offset
**Returns**:
`QuerysetProxy`: QuerysetProxy
#### fields
```python
| fields(columns: Union[List, str, Set, Dict]) -> "QuerysetProxy[T]"
```
With `fields()` you can select subset of model columns to limit the data load.
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).
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.]`.
`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.
Mandatory fields cannot be excluded as it will raise `ValidationError`,
to exclude a field it has to be nullable.
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.
Actual call delegated to QuerySet.
**Arguments**:
- `columns` (`Union[List, str, Set, Dict]`): columns to include
**Returns**:
`QuerysetProxy`: QuerysetProxy
#### exclude\_fields
```python
| exclude_fields(columns: Union[List, str, Set, Dict]) -> "QuerysetProxy[T]"
```
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 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).
Mandatory fields cannot be excluded as it will raise `ValidationError`,
to exclude a field it has to be nullable.
Pk column cannot be excluded - it's always auto added even
if explicitly excluded.
Actual call delegated to QuerySet.
**Arguments**:
- `columns` (`Union[List, str, Set, Dict]`): columns to exclude
**Returns**:
`QuerysetProxy`: QuerysetProxy
#### order\_by
```python
| order_by(columns: Union[List, str, "OrderAction"]) -> "QuerysetProxy[T]"
```
With `order_by()` you can order the results from database based on your
choice of fields.
You can provide a string with field name or list of strings with fields names.
Ordering in sql will be applied in order of names you provide in order_by.
By default if you do not provide ordering `ormar` explicitly orders by
all primary keys
If you are sorting by nested models that causes that the result rows are
unsorted by the main model `ormar` will combine those children rows into
one main model.
The main model will never duplicate in the result
To order by main model field just provide a field name
To sort on nested models separate field names with dunder '__'.
You can sort this way across all relation types -> `ForeignKey`,
reverse virtual FK and `ManyToMany` fields.
To sort in descending order provide a hyphen in front of the field name
Actual call delegated to QuerySet.
**Arguments**:
- `columns` (`Union[List, str]`): columns by which models should be sorted
**Returns**:
`QuerysetProxy`: QuerysetProxy