Skip to content

relations.querysetproxy

QuerysetProxy Objects

1
class QuerysetProxy(Generic[T])

Exposes QuerySet methods on relations, but also handles creating and removing of through Models for m2m relations.

queryset

1
2
 | @property
 | queryset() -> "QuerySet[T]"

Returns queryset if it's set, AttributeError otherwise.

Returns:

QuerySet :rtype: QuerySet

queryset

1
2
 | @queryset.setter
 | queryset(value: "QuerySet") -> None

Set's the queryset. Initialized in RelationProxy.

Arguments:

  • value: QuerySet :type value: QuerySet

_assign_child_to_parent

1
 | _assign_child_to_parent(child: Optional["T"]) -> None

Registers child in parents RelationManager.

Arguments:

  • child: child to register on parent side. :type child: Model

1
 | _register_related(child: Union["T", Sequence[Optional["T"]]]) -> None

Registers child/ children in parents RelationManager.

Arguments:

  • child: child or list of children models to register. :type child: Union[Model,List[Model]]

_clean_items_on_load

1
 | _clean_items_on_load() -> None

Cleans the current list of the related models.

create_through_instance

1
 | async create_through_instance(child: "T", **kwargs: Any) -> None

Crete a through model instance in the database for m2m relations.

Arguments:

  • kwargs: dict of additional keyword arguments for through instance :type kwargs: Any
  • child: child model instance :type child: Model

update_through_instance

1
 | async update_through_instance(child: "T", **kwargs: Any) -> None

Updates a through model instance in the database for m2m relations.

Arguments:

  • kwargs: dict of additional keyword arguments for through instance :type kwargs: Any
  • child: child model instance :type child: Model

upsert_through_instance

1
 | 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: dict of additional keyword arguments for through instance :type kwargs: Any
  • child: child model instance :type child: Model

delete_through_instance

1
 | async delete_through_instance(child: "T") -> None

Removes through model instance from the database for m2m relations.

Arguments:

  • child: child model instance :type child: Model

exists

1
 | 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:

result of the check :rtype: bool

count

1
 | 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:

number of rows :rtype: int

max

1
 | 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:

max value of column(s) :rtype: Any

min

1
 | 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:

min value of column(s) :rtype: Any

sum

1
 | 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:

sum value of columns :rtype: int

avg

1
 | 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:

avg value of columns :rtype: Union[int, float, List]

clear

1
 | 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:

  • keep_reversed: flag if reverse models in reverse FK should be deleted or not, keep_reversed=False deletes them from database. :type keep_reversed: bool

Returns:

number of deleted models :rtype: int

values

1
 | async values(fields: Union[List, str, Set, Dict] = None, exclude_through: bool = False) -> List

Return a list of dictionaries with column values in order of the fields passed or all fields from queried models.

To filter for given row use filter/exclude methods before values, to limit number of rows use limit/offset or paginate before values.

Note that it always return a list even for one row from database.

Arguments:

  • exclude_through: flag if through models should be excluded :type exclude_through: bool
  • fields: field name or list of field names to extract from db :type fields: Union[List, str, Set, Dict]

values_list

1
 | async values_list(fields: Union[List, str, Set, Dict] = None, flatten: bool = False, exclude_through: bool = False) -> List

Return a list of tuples with column values in order of the fields passed or all fields from queried models.

When one field is passed you can flatten the list of tuples into list of values of that single field.

To filter for given row use filter/exclude methods before values, to limit number of rows use limit/offset or paginate before values.

Note that it always return a list even for one row from database.

Arguments:

  • exclude_through: flag if through models should be excluded :type exclude_through: bool
  • fields: field name or list of field names to extract from db :type fields: Union[str, List[str]]
  • flatten: when one field is passed you can flatten the list of tuples :type flatten: bool

first

1
 | 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: :type kwargs:

Returns:

:rtype: _asyncio.Future

get_or_none

1
 | 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: fields names and proper value types :type kwargs: Any

Returns:

returned model :rtype: Model

get

1
 | 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: fields names and proper value types :type kwargs: Any

Returns:

returned model :rtype: Model

all

1
 | 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: fields names and proper value types :type kwargs: Any

Returns:

list of returned models :rtype: List[Model]

create

1
 | 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: fields names and proper value types :type kwargs: Any

Returns:

created model :rtype: Model

update

1
 | 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: flag if whole table should be affected if no filter is passed :type each: bool
  • kwargs: fields names and proper value types :type kwargs: Any

Returns:

number of updated rows :rtype: int

get_or_create

1
 | 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: fields names and proper value types :type kwargs: Any

Returns:

returned or created Model :rtype: Model

update_or_create

1
 | 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: fields names and proper value types :type kwargs: Any

Returns:

updated or created model :rtype: Model

filter

1
 | 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: fields names and proper value types :type kwargs: Any

Returns:

filtered QuerysetProxy :rtype: QuerysetProxy

exclude

1
 | 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: fields names and proper value types :type kwargs: Any

Returns:

filtered QuerysetProxy :rtype: QuerysetProxy

select_all

1
 | 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:

  • follow: flag to trigger deep save - by default only directly related models are saved with follow=True also related models of related models are saved :type follow: bool

Returns:

reloaded Model :rtype: Model

1
 | 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: list of relation field names, can be linked by '__' to nest :type related: Union[List, str]

Returns:

QuerysetProxy :rtype: QuerysetProxy

1
 | 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: list of relation field names, can be linked by '__' to nest :type related: Union[List, str]

Returns:

QuerysetProxy :rtype: QuerysetProxy

paginate

1
 | 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: numbers of items per page :type page_size: int
  • page: page number :type page: int

Returns:

QuerySet :rtype: QuerySet

limit

1
 | 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: number of models to limit :type limit_count: int

Returns:

QuerysetProxy :rtype: QuerysetProxy

offset

1
 | offset(offset: int) -> "QuerysetProxy[T]"

You can also offset the results by desired number of main models.

Actual call delegated to QuerySet.

Arguments:

  • offset: numbers of models to offset :type offset: int

Returns:

QuerysetProxy :rtype: QuerysetProxy

fields

1
 | 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: columns to include :type columns: Union[List, str, Set, Dict]

Returns:

QuerysetProxy :rtype: QuerysetProxy

exclude_fields

1
 | 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: columns to exclude :type columns: Union[List, str, Set, Dict]

Returns:

QuerysetProxy :rtype: QuerysetProxy

order_by

1
 | 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: columns by which models should be sorted :type columns: Union[List, str]

Returns:

QuerysetProxy :rtype: QuerysetProxy