API
Module queryable_properties.properties
- class queryable_properties.properties.AggregateProperty(aggregate, **kwargs)[source]
A property that is based on an aggregate that is used to provide both queryset annotations and getter values.
- class queryable_properties.properties.AnnotationProperty(annotation, **kwargs)[source]
A property that is based on a static annotation that is even used to provide getter values.
- class queryable_properties.properties.RelatedExistenceCheckProperty(relation_path, negated=False, **kwargs)[source]
A property that checks whether related objects to the one that uses the property exist in the database and returns a corresponding boolean value.
Supports queryset filtering and
CASE/WHEN-based annotating.- __init__(relation_path, negated=False, **kwargs)[source]
Initialize a new property that checks for the existence of related objects.
- Parameters:
relation_path (str) – The path to the object/field whose existence is to be checked. May contain the lookup separator (
__) to check for more remote relations.negated (bool) – If
True, the property will check for the non-existence of the related objects instead. Defaults toFalse.
- class queryable_properties.properties.QueryableProperty(verbose_name=None)[source]
Base class for all queryable property definitions, which provide methods for single object as well as queryset interaction.
- cached = False
Determines if the result of the getter is cached, like Python’s/Django’s
cached_property.
- filter_requires_annotation = False
Determines if using the property to filter requires annotating first.
- __init__(verbose_name=None)[source]
Initialize a new queryable property.
- Parameters:
verbose_name (str) – An optional verbose name of the property. If not provided it defaults to a prettified version of the property’s name.
- setter_cache_behavior(obj, value, return_value)
Determines what happens if the setter of a cached property is used.
- property short_description
Return the verbose name of this property as its short description, which is required for the admin integration.
- Returns:
The verbose name of this property.
- Return type:
str
- get_value(obj)[source]
Getter method for the queryable property, which will be called when the property is read-accessed.
- Parameters:
obj (django.db.models.Model) – The object on which the property was accessed.
- Returns:
The getter value.
- get_filter(cls, lookup, value)[source]
Generate a
django.db.models.Qobject that emulates filtering a queryset using this property.- Parameters:
cls (type) – The model class of which a queryset should be filtered.
lookup (str) – The lookup to use for the filter (e.g. ‘exact’, ‘lt’, etc.)
value – The value passed to the filter condition.
- Returns:
A Q object to filter using this property.
- Return type:
django.db.models.Q
- class queryable_properties.properties.queryable_property(getter=None, cached=None, annotation_based=False, **kwargs)[source]
A queryable property that is intended to be used as a decorator.
- get_value = None
- get_filter = None
- __init__(getter=None, cached=None, annotation_based=False, **kwargs)[source]
Initialize a new queryable property, optionally using the given getter method and getter configuration.
- Parameters:
getter (function) – The method to decorate.
cached (bool | None) – Determines if values obtained by the getter should be cached (similar to
cached_property). A value of None means using the default value.annotation_based (bool) – If True, the
AnnotationGetterMixinis automatically added to this property to define a getter implementation and this property is expected to decorate the annotater method instead of the getter. If False, property is expected to decorate the getter method.
- getter(method, cached=None)[source]
Decorator for a function or method that is used as the getter of this queryable property. May be used as a parameter-less decorator (
@getter) or as a decorator with keyword arguments (@getter(cached=True)).- Parameters:
method (function) – The method to decorate.
cached (bool | None) – If
True, values returned by the decorated getter method will be cached. A value of None means no change.
- Returns:
A cloned queryable property.
- Return type:
- setter(method, cache_behavior=None)[source]
Decorator for a function or method that is used as the setter of this queryable property. May be used as a parameter-less decorator (
@setter) or as a decorator with keyword arguments (@setter(cache_behavior=DO_NOTHING)).- Parameters:
method (function) – The method to decorate.
cache_behavior (function | None) – A function that defines how the setter interacts with cached values. A value of None means no change.
- Returns:
A cloned queryable property.
- Return type:
- filter(method, requires_annotation=None, lookups=None, boolean=False, remaining_lookups_via_parent=None)[source]
Decorator for a function or method that is used to generate a filter for querysets to emulate filtering by this queryable property. May be used as a parameter-less decorator (
@filter) or as a decorator with keyword arguments (@filter(requires_annotation=False)). May be used to define a one-for-all filter function or a filter function that will be called for certain lookups only using thelookupsargument.- Parameters:
method (function | classmethod | staticmethod) – The method to decorate.
requires_annotation (bool | None) –
Trueif filtering using this queryable property requires its annotation to be applied first; otherwiseFalse. None if this information should not be changed.lookups (collections.Iterable[str] | None) – If given, the decorated function or method will be used for the specified lookup(s) only. Automatically adds the
LookupFilterMixinto this property if this is used.boolean (bool) – If
True, the decorated function or method is expected to be a simple boolean filter, which doesn’t take thelookupandvalueparameters and should always return aQobject representing the positive (i.e.True) filter case. The decorator will automatically negate the condition if the filter was called with aFalsevalue.remaining_lookups_via_parent (bool) –
Trueif lookup-based filters should fall back to the base class implementation for lookups without a registered filter function; otherwiseFalse. None if this information should not be changed.
- Returns:
A cloned queryable property.
- Return type:
- annotater(method)[source]
Decorator for a function or method that is used to generate an annotation to represent this queryable property in querysets. The
AnnotationMixinwill automatically be applied to this property when this decorator is used.- Parameters:
method (function | classmethod | staticmethod) – The method to decorate.
- Returns:
A cloned queryable property.
- Return type:
- updater(method)[source]
Decorator for a function or method that is used to resolve an update keyword argument for this queryable property into the actual update keyword arguments.
- Parameters:
method (function | classmethod | staticmethod) – The method to decorate.
- Returns:
A cloned queryable property.
- Return type:
- queryable_properties.properties.CACHE_RETURN_VALUE(descriptor, obj, value, return_value)[source]
Setter cache behavior function that will update the cache for the cached queryable property on the object in question with the return value of the setter function/method.
- Parameters:
descriptor (queryable_properties.properties.base.QueryablePropertyDescriptor) – The descriptor of the property whose setter was used.
obj (django.db.models.Model) – The object the setter was used on.
value – The value that was passed to the setter.
return_value – The return value of the setter function/method.
- queryable_properties.properties.CACHE_VALUE(descriptor, obj, value, return_value)[source]
Setter cache behavior function that will update the cache for the cached queryable property on the object in question with the (raw) value that was passed to the setter.
- Parameters:
descriptor (queryable_properties.properties.base.QueryablePropertyDescriptor) – The descriptor of the property whose setter was used.
obj (django.db.models.Model) – The object the setter was used on.
value – The value that was passed to the setter.
return_value – The return value of the setter function/method.
- queryable_properties.properties.CLEAR_CACHE(descriptor, obj, value, return_value)[source]
Setter cache behavior function that will clear the cached value for a cached queryable property on objects after the setter was used.
- Parameters:
descriptor (queryable_properties.properties.base.QueryablePropertyDescriptor) – The descriptor of the property whose setter was used.
obj (django.db.models.Model) – The object the setter was used on.
value – The value that was passed to the setter.
return_value – The return value of the setter function/method.
- queryable_properties.properties.DO_NOTHING(descriptor, obj, value, return_value)[source]
Setter cache behavior function that will do nothing after the setter of a cached queryable property was used, retaining previously cached values.
- Parameters:
descriptor (queryable_properties.properties.base.QueryablePropertyDescriptor) – The descriptor of the property whose setter was used.
obj (django.db.models.Model) – The object the setter was used on.
value – The value that was passed to the setter.
return_value – The return value of the setter function/method.
- class queryable_properties.properties.ContentTypeProperty(**kwargs)[source]
A property that allows to determine the content type of model instances.
- __init__(**kwargs)[source]
Initialize a new property that allows to determine the content type of model instances.
- Parameters:
depth – The maximum depth of the inheritance hierarchy to follow. Instances of model classes below this maximum depth will be treated as objects of the maximum depth. If not provided, no maximum depth will be enforced.
field_names – The names of the fields that should be queried for content type objects. Fields not present in this sequence will be deferred. If not provided, all concrete content type fields will be queried.
- class queryable_properties.properties.InheritanceModelProperty(value_generator, output_field, **kwargs)[source]
A property that returns information about the actual model class of objects in inheritance scenarios.
- __init__(value_generator, output_field, **kwargs)[source]
Initialize a new property that returns information about the actual model class of objects in inheritance scenarios.
- Parameters:
value_generator (function) – A callable that returns the actual value to be represented for a given model class. Must take a model class as its first argument.
output_field (django.db.models.Field) – The output field to use for this property, which must be able to hold the values generated by the given value generator.
depth – The maximum depth of the inheritance hierarchy to follow. Instances of model classes below this maximum depth will be treated as objects of the maximum depth. If not provided, no maximum depth will be enforced.
- class queryable_properties.properties.InheritanceObjectProperty(**kwargs)[source]
A property that returns the final submodel instance in inheritance scenarios.
- __init__(**kwargs)[source]
Initialize a new property that returns the final submodel instance in inheritance scenarios.
- Parameters:
depth – The maximum depth of the inheritance hierarchy to follow. Instances of model classes below this maximum depth will be treated as objects of the maximum depth. If not provided, no maximum depth will be enforced.
- class queryable_properties.properties.AnnotationGetterMixin(cached=None, *args, **kwargs)[source]
A mixin for queryable properties that support annotation and use their annotation even to provide the value for their getter (i.e. perform a query to retrieve the getter value).
- __init__(cached=None, *args, **kwargs)[source]
Initialize a new queryable property based that uses the
AnnotationGetterMixin.- Parameters:
cached – Determines if values obtained by the getter should be cached (similar to
cached_property). A value of None means using the default value.
- get_queryset(model)[source]
Construct a base queryset for the given model class that can be used to build queries in property code.
- Parameters:
model – The model class to build the queryset for.
- get_queryset_for_object(obj)[source]
Construct a base queryset that can be used to retrieve the getter value for the given object.
- Parameters:
obj (django.db.models.Model) – The object to build the queryset for.
- Returns:
A base queryset for the correct model that is already filtered for the given object.
- Return type:
django.db.models.QuerySet
- class queryable_properties.properties.AnnotationMixin(*args, **kwargs)[source]
A mixin for queryable properties that allows to add an annotation to represent them to querysets.
- property admin_order_field
Return the field name for the ordering in the admin, which is simply the property’s name since it’s annotatable.
- Returns:
The field name for ordering in the admin.
- Return type:
str
- queryable_properties.properties.boolean_filter(method)
Decorator for individual filter methods of classes that use the
LookupFilterMixinto register the methods that are simple boolean filters (i.e. the filter can only be called with aTrueorFalsevalue). This automatically restricts the usable lookups toexact. Decorated methods should not expect thelookupandvalueparameters and should always return aQobject representing the positive (i.e.True) filter case. The decorator will automatically negate the condition if the filter was called with aFalsevalue.- Parameters:
method (function) – The method to decorate.
- Returns:
The decorated method.
- Return type:
function
- class queryable_properties.properties.LookupFilterMixin(*args, **kwargs)[source]
A mixin for queryable properties that allows to implement queryset filtering via individual methods for different lookups.
- classmethod lookup_filter(*lookups)[source]
Decorator for individual filter methods of classes that use the
LookupFilterMixinto register the decorated methods for the given lookups.- Parameters:
lookups (str) – The lookups to register the decorated method for.
- Returns:
The actual internal decorator.
- Return type:
function
- classmethod boolean_filter(method)[source]
Decorator for individual filter methods of classes that use the
LookupFilterMixinto register the methods that are simple boolean filters (i.e. the filter can only be called with aTrueorFalsevalue). This automatically restricts the usable lookups toexact. Decorated methods should not expect thelookupandvalueparameters and should always return aQobject representing the positive (i.e.True) filter case. The decorator will automatically negate the condition if the filter was called with aFalsevalue.- Parameters:
method (function) – The method to decorate.
- Returns:
The decorated method.
- Return type:
function
- queryable_properties.properties.lookup_filter(*lookups)
Decorator for individual filter methods of classes that use the
LookupFilterMixinto register the decorated methods for the given lookups.- Parameters:
lookups (str) – The lookups to register the decorated method for.
- Returns:
The actual internal decorator.
- Return type:
function
- class queryable_properties.properties.SetterMixin[source]
A mixin for queryable properties that also define a setter.
- class queryable_properties.properties.UpdateMixin[source]
A mixin for queryable properties that allows to use themselves in update queries.
- get_update_kwargs(cls, value)[source]
Resolve an update keyword argument for this property into the actual keyword arguments to emulate an update using this property.
- Parameters:
cls (type) – The model class of which an update query should be performed.
value – The value passed to the update call for this property.
- Returns:
The actual keyword arguments to set in the update call instead of the given one.
- Return type:
dict
- class queryable_properties.properties.MappingProperty(attribute_path, output_field, mappings, default=None, **kwargs)[source]
A property that translates values of an attribute into other values using defined mappings.
- __init__(attribute_path, output_field, mappings, default=None, **kwargs)[source]
Initialize a property that maps values from an attribute to other values.
- Parameters:
attribute_path (str) – The name of the attribute to compare against. May also be a more complex path to a related attribute using dot-notation (like with
operator.attrgetter()). If an intermediate value on the path is None, it will be treated as “no match” instead of raising an exception. The behavior is the same if an intermediate value raises anObjectDoesNotExisterror.output_field (django.db.models.Field) – The field to represent the mapped values in querysets.
mappings (collections.Iterable[(object, object)]) – An iterable containing 2-tuples that represent the mappings to use (the first value is the expected attribute value, the second value is the translated value). Needs to be able to be iterated multiple times as the whole iterable is evaluated any time the property is accessed on an object or in queries (generators can thus not be used).
default – A default value to return/use in querysets when in case none of the mappings match an encountered value. Defaults to None.
- class queryable_properties.properties.RangeCheckProperty(min_attribute_path, max_attribute_path, value, include_boundaries=True, in_range=True, include_missing=False, **kwargs)[source]
A property that checks if a static or dynamic value is contained in a range expressed by two field values and returns a corresponding boolean value.
Supports queryset filtering and
CASE/WHEN-based annotating.- __init__(min_attribute_path, max_attribute_path, value, include_boundaries=True, in_range=True, include_missing=False, **kwargs)[source]
Initialize a new property that checks if a value is contained in a range expressed by two field values.
- Parameters:
min_attribute_path (str) – The name of the attribute to get the lower boundary from. May also be a more complex path to a related attribute using dot-notation (like with
operator.attrgetter()). If an intermediate value on the path is None, it will be treated as a missing value instead of raising an exception. The behavior is the same if an intermediate value raises anObjectDoesNotExisterror.max_attribute_path (str) – The name of the attribute to get the upper boundary from. The same behavior as for the lower boundary applies.
value – The value which is tested against the boundary. May be a callable which can be called without any arguments, whose return value will then be used as the test value.
include_boundaries (bool) – Whether the value is considered a part of the range if it is exactly equal to one of the boundaries.
in_range (bool) – Configures whether the property should return
Trueif the value is in range (in_range=True) or if it is out of the range (in_range=False). This also affects the impact of theinclude_boundariesandinclude_missingparameters.include_missing (bool) – Whether a missing value is considered a part of the range (see the description of
min_attribute_path). Useful e.g. for nullable fields.
- class queryable_properties.properties.ValueCheckProperty(attribute_path, *values, **kwargs)[source]
A property that checks if an attribute of a model instance or a related object contains a certain value or one of multiple specified values and returns a corresponding boolean value.
Supports queryset filtering and
CASE/WHEN-based annotating.- __init__(attribute_path, *values, **kwargs)[source]
Initialize a new property that checks for certain field values.
- Parameters:
attribute_path (str) – The name of the attribute to compare against. May also be a more complex path to a related attribute using dot-notation (like with
operator.attrgetter()). If an intermediate value on the path is None, it will be treated as “no match” instead of raising an exception. The behavior is the same if an intermediate value raises an ObjectDoesNotExist error.values – The value(s) to check for.
- class queryable_properties.properties.SubqueryExistenceCheckProperty(queryset, negated=False, **kwargs)[source]
A property that checks whether certain objects exist in the database using a custom subquery.
- __init__(queryset, negated=False, **kwargs)[source]
Initialize a new property that checks for the existence of database records using a custom subquery.
- Parameters:
queryset (django.db.models.QuerySet | function) – The internal queryset to use as the subquery or a callable that takes no arguments or the outer model class as its sole argument and generates the internal queryset.
negated (bool) – Whether to negate the
EXISTSsubquery (i.e. the property will returnTrueif no objects exist when usingnegated=True).
- class queryable_properties.properties.SubqueryFieldProperty(queryset, field_name, output_field=None, **kwargs)[source]
A property that returns a field value contained in a subquery, extracting it from the first row of the subquery’s result set.
- __init__(queryset, field_name, output_field=None, **kwargs)[source]
Initialize a new property that returns a field value from a subqery.
- Parameters:
queryset (django.db.models.QuerySet | function) – The internal queryset to use as the subquery or a callable that takes no arguments or the outer model class as its sole argument and generates the internal queryset.
field_name (str) – The name of the subquery field whose value should be returned. May refer to an annotated field or queryable property inside the subquery.
output_field (django.db.models.Field | None) – The output field to use for the subquery expression. Only required in cases where Django cannot determine the field type on its own.
- class queryable_properties.properties.SubqueryObjectProperty(model, queryset, field_names=None, property_names=(), **kwargs)[source]
A property that allows to fetch an entire model object from the first row of a given subquery.
Each field value of the subquery object is queried using a
SubqueryFieldProperty. A model instance is reconstructed from the individual field values.- __init__(model, queryset, field_names=None, property_names=(), **kwargs)[source]
Initialize a new property that allows to fetch an entire model object from the first row of a given subquery.
- Parameters:
model (type | str) – The model class whose instances are being queried via the subquery. Can be either a concrete model class or a lazy reference to a model class (see foreign keys).
queryset (django.db.models.QuerySet | function) – The internal queryset to use as the subquery or a callable that takes no arguments or the outer model class as its sole argument and generates the internal queryset.
field_names (collections.Sequence[str] | None) – The names of the fields that should be queried for the subquery object. Fields not present in this sequence will be deferred. If not provided, all concrete fields of the model will be queried.
property_names (collections.Sequence[str]) – Optional names of queryable properties on the subquery model whose values should be retrieved along with the other fields. If not provided, no queryable property values will be selected.
Module queryable_properties.admin
- class queryable_properties.admin.QueryablePropertiesAdmin(model, admin_site)[source]
Base class for admin classes which allows to use queryable properties in various admin features.
Intended to be used in place of Django’s regular
ModelAdminclass.
- class queryable_properties.admin.QueryablePropertiesAdminMixin[source]
A mixin for admin classes including inlines that allows to use queryable properties in various admin features.
- list_select_properties = ()
A sequence of queryable property names that should be selected.
- get_list_select_properties(request)[source]
Wrapper around the
list_select_propertiesattribute that allows to dynamically create the list of queryable property names to select based on the given request.- Parameters:
request (django.http.HttpRequest) – The request to the admin.
- Returns:
A sequence of queryable property names to select.
- Return type:
collections.Sequence[str]
- process_queryable_property_filters(list_filter)[source]
Process a sequence of list filters to create a new sequence in which queryable property references are replaced with custom callables that make them compatible with Django’s filter workflow.
- Parameters:
list_filter (collections.Sequence) – The list filter sequence.
- Returns:
The processed list filter sequence.
- Return type:
list
Module queryable_properties.managers
- class queryable_properties.managers.QueryablePropertiesManager(*args, **kwargs)[source]
A special manager class that allows to use queryable properties methods and returns
QueryablePropertiesQuerySetinstances.- classmethod get_for_model(model, using=None, hints=None)[source]
Get a new manager with queryable properties functionality for the given model.
- Parameters:
model – The model class for which the manager should be built.
using (str | None) – An optional name of the database connection to use.
hints (dict | None) – Optional hints for the db connection.
- Returns:
A new manager with queryable properties functionality.
- Return type:
- class queryable_properties.managers.QueryablePropertiesManagerMixin(*args, **kwargs)[source]
A mixin for Django’s
django.db.models.Managerobjects that allows to use queryable properties methods and returnsQueryablePropertiesQuerySetinstances.- classmethod apply_to(manager)[source]
Copy the given manager and apply this mixin (and thus queryable properties functionality) to it, returning a new manager that allows to use queryable property interaction.
- Parameters:
manager (Manager) – The manager to apply this mixin to.
- Returns:
A copy of the given manager with queryable properties functionality.
- Return type:
- select_properties(*names)[source]
Return a new queryset and add the annotations of the queryable properties with the specified names to this query. The annotation values will be cached in the properties of resulting model instances, regardless of the regular caching behavior of the queried properties.
- Parameters:
names – Names of queryable properties.
- Returns:
A copy of this queryset with the added annotations.
- Return type:
QuerySet
- class queryable_properties.managers.QueryablePropertiesQuerySet(*args, **kwargs)[source]
A special queryset class that allows to use queryable properties in its filter conditions, annotations and update queries.
- classmethod get_for_model(model)[source]
Get a new queryset with queryable properties functionality for the given model. The queryset is built using the model’s default manager.
- Parameters:
model – The model class for which the queryset should be built.
- Returns:
A new queryset with queryable properties functionality.
- Return type:
- class queryable_properties.managers.QueryablePropertiesQuerySetMixin(*args, **kwargs)[source]
A mixin for Django’s
django.db.models.QuerySetobjects that allows to use queryable properties in filters, annotations and update queries.- classmethod apply_to(queryset)[source]
Copy the given queryset and apply this mixin (and thus queryable properties functionality) to it, returning a new queryset that allows to use queryable property interaction.
- Parameters:
queryset (QuerySet) – The queryset to apply this mixin to.
- Returns:
A copy of the given queryset with queryable properties functionality.
- Return type:
- init_injected_attrs()[source]
Initialize the attributes this mixin contributes. This method will be called during
__init__()and after the mixin was injected into an object.
- select_properties(*names)[source]
Add the annotations of the queryable properties with the specified names to this query. The annotation values will be cached in the properties of resulting model instances, regardless of the regular caching behavior of the queried properties.
- Parameters:
names – Names of queryable properties.
- Returns:
A copy of this queryset with the added annotations.
- Return type:
QuerySet
Module queryable_properties.utils
- queryable_properties.utils.get_queryable_property(model, name)[source]
Retrieve the
queryable_properties.properties.QueryablePropertyobject with the given attribute name from the given model class or raise an error if no queryable property with that name exists on the model class.- Parameters:
model (type | django.db.models.Model | str) – The model to retrieve the property object from. May be specified as the model class, a model instance or a string containing Django’s
<app_label>.<model_name>format.name (str) – The name of the property to retrieve.
- Returns:
The queryable property.
- Return type:
- queryable_properties.utils.prefetch_queryable_properties(model_instances, *property_paths)[source]
Populate the queryable property caches for a list of model instances based on the given property paths.
- Parameters:
model_instances (collections.Sequence) – The model instances to prefetch the property values for. The instances may be objects of different models as long as the given property paths are valid for all of them.
property_paths (str) – The paths to the properties whose values should be fetched, which are need to be annotatable. The paths may contain the lookup separator to fetch values of properties on related objects (make sure that the related objects are already prefetched to avoid additional queries).
- queryable_properties.utils.reset_queryable_property(obj, name)[source]
Reset the cached value of the queryable property with the given name on the given model instance. Read-accessing the property on this model instance at a later point will therefore execute the property’s getter again.
- Parameters:
obj (django.db.models.Model) – The model instance to reset the cached value on.
name (str) – The name of the queryable property.