QuerySets and Managers
KML ORM provides Django-style QuerySets and Managers for filtering and querying KML elements. Managers serve as the interface between models and the database-like operations, providing access to QuerySets which handle the actual filtering, chaining, and data manipulation. When you call methods like .filter() or .all() on a manager, it returns a QuerySet that can be further refined with additional filters and operations. This two-tier system allows for intuitive, chainable queries while maintaining clean separation between data access (Managers) and data manipulation (QuerySets).
QuerySet
A QuerySet represents a collection of KML elements that can be filtered, ordered, and manipulated through a fluent interface. The term “QuerySet” originates from Django’s ORM, where it describes a lazy, chainable container for database queries that doesn’t execute until the data is actually needed. In KML ORM, QuerySets work similarly but operate on in-memory KML data rather than database records.
QuerySets are lazy and chainable, meaning you can apply multiple filters, ordering operations, and transformations without immediately processing the data. The actual filtering and processing occurs when you iterate over the QuerySet, access specific elements, or call evaluation methods. This design allows for efficient composition of complex queries and provides an intuitive interface for data manipulation that feels natural to developers familiar with Django or similar ORMs.
The KMLQuerySet class provides chainable query methods.
Django-style QuerySet implementation for KML elements.
This module provides the KMLQuerySet class that implements all the query methods like filter(), exclude(), get(), etc. in a Django-compatible way.
- class kmlorm.core.querysets.KMLQuerySet(elements=None)[source]
Bases:
Generic[T]Typed QuerySet for KML elements.
This class wraps a list of elements and implements the common query/filter operations. It is generic in the element type so callers receive precise T / Optional[T] / List[T] return types.
Similar to Django’s QuerySet.
- __init__(elements=None)[source]
Initialize a QuerySet with a list of elements.
- __getitem__(key)[source]
Support indexing and slicing of QuerySet.
- property elements: List[T]
Returns the list of KMLElement objects associated with this queryset.
- Returns:
- A list of KMLElement instances if available, otherwise
None.
- Return type:
Optional[List[“KMLElement”]]
- all()[source]
Return a copy of this QuerySet.
This method exists for Django compatibility and returns a new QuerySet with the same elements.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]
- filter(**kwargs)[source]
Filter elements based on field lookups.
Supports Django-style field lookups like: - name__icontains=’capital’ - coordinates__latitude__gte=39.0 - visibility=True
- property is_ordered: bool
Returns whether the queryset is ordered.
- Returns:
True if the queryset has an ordering applied, False otherwise.
- Return type:
- property order_by_fields: List[str]
Returns the list of field names used to determine the ordering of query results.
- Returns:
- A list of strings representing the field names by which the results are
ordered.
- Return type:
List[str]
- property is_distinct: bool
Returns whether the queryset is marked to return distinct results.
- Returns:
True if the queryset is set to return distinct results, False otherwise.
- Return type:
- exclude(**kwargs)[source]
Exclude elements that match the given filters.
This is the inverse of filter() - returns elements that do NOT match the criteria.
- get(**kwargs)[source]
Get a single element that matches the given criteria.
- Parameters:
**kwargs (
Any) – Field lookup expressions- Return type:
TypeVar(T, bound= KMLElement)- Returns:
Single matching KML element
- Raises:
KMLElementNotFound – If no elements match
KMLMultipleElementsReturned – If multiple elements match
- first()[source]
Get the first element in the QuerySet.
- last()[source]
Get the last element in the QuerySet.
- count()[source]
Return the number of elements in the QuerySet.
- Return type:
- Returns:
Number of elements
- exists()[source]
Check if the QuerySet contains any elements.
- Return type:
- Returns:
True if QuerySet has elements, False otherwise
- none()[source]
Return an empty QuerySet.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]- Returns:
Empty QuerySet of the same type
- order_by(*fields)[source]
Order elements by the given fields.
Supports field names with optional ‘-’ prefix for descending order.
- reverse()[source]
Reverse the order of elements.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]- Returns:
New QuerySet with reversed element order
- distinct()[source]
Remove duplicate elements.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]- Returns:
New QuerySet with unique elements only
- values(*fields)[source]
Return a list of dictionaries with specified field values.
- values_list(*fields, flat=False)[source]
Return a list of tuples with specified field values.
- near(longitude, latitude, radius_km=None)[source]
Filter elements within a radius of given coordinates.
- within_bounds(north, south, east, west)[source]
Filter elements within a bounding box.
- Parameters:
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]- Returns:
New QuerySet with elements in bounds
- has_coordinates()[source]
Filter elements that have coordinate data.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]- Returns:
New QuerySet with elements that have coordinates
- valid_coordinates()[source]
Filter elements with valid coordinate ranges.
Uses the Coordinate class validation to ensure consistency with the authoritative coordinate validation logic.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]- Returns:
New QuerySet with elements having valid coordinates
Manager
A Manager is the interface between KML models and QuerySets, serving as the primary access point for retrieving and manipulating collections of KML elements. The term “Manager” comes from Django’s ORM, where it represents the layer responsible for managing database table operations and providing the entry point for queries. In Django, managers are accessed through the .objects attribute on models, establishing a clean separation between the model definition and query operations.
In KML ORM, managers work similarly but are tailored for KML data structures. Each KML element type has its own specialized manager that provides type-safe access to QuerySets. Managers handle the initial data access and creation of QuerySets, while also providing convenience methods for common operations. They act as the bridge between the high-level model interface and the low-level query operations, ensuring that all data access follows consistent patterns and maintains proper type safety throughout the query chain.
The KMLManager class provides the interface for accessing QuerySets.
Django-style Manager classes for KML elements.
This module provides the KMLManager and RelatedManager classes that implement the .objects interface and relationship management similar to Django’s ORM managers.
- class kmlorm.core.managers.KMLManager(folders_manager=None)[source]
Bases:
Generic[T]Django-style manager for KML elements.
Provides the .objects interface that returns QuerySets for chaining queries and filtering operations.
- __init__(folders_manager=None)[source]
Initialize the manager.
- Parameters:
folders_manager (
Optional[KMLManager[Folder]]) – Reference to the folders manager for flattening operations
- property elements: List[T]
Returns a list of KMLElement objects managed by this instance.
- Returns:
The list of KMLElement objects.
- Return type:
list[KMLElement]
- contribute_to_class(model_class, name)[source]
Called when manager is attached to a model class.
- get_queryset()[source]
Return a QuerySet containing all elements.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]- Returns:
QuerySet with all managed elements
- all()[source]
Return all elements as a QuerySet, including those in nested folders.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]- Returns:
QuerySet containing all elements including those in nested folders
Example
>>> # Get all placemarks including those in nested folders >>> all_placemarks = kml.placemarks.all() >>> >>> # For direct children only, use .children() >>> root_placemarks = kml.placemarks.children()
- children()[source]
Return only direct child elements as a QuerySet.
This method returns elements that are direct children of the current container, without traversing into nested folders. This provides the same behavior as the current .all() method without the flatten parameter.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]- Returns:
QuerySet containing only direct child elements
Example
>>> # Get only placemarks directly in the KML file root >>> root_placemarks = kml_file.placemarks.children() >>> >>> # Get only folders directly in the current folder >>> direct_subfolders = folder.folders.children() >>> >>> # Chain with other QuerySet methods >>> visible_root_placemarks = kml_file.placemarks.children().filter(visibility=True)
- filter(**kwargs)[source]
Filter elements based on field lookups.
- exclude(**kwargs)[source]
Exclude elements that match the given filters.
- get(**kwargs)[source]
Get a single element that matches the criteria.
- Parameters:
**kwargs (
Any) – Field lookup expressions- Return type:
TypeVar(T, bound= KMLElement)- Returns:
Single matching element
- Raises:
KMLElementNotFound – If no elements match
KMLMultipleElementsReturned – If multiple elements match
- first()[source]
Get the first element.
- last()[source]
Get the last element.
- none()[source]
Return an empty QuerySet.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]- Returns:
Empty QuerySet
- order_by(*fields)[source]
Order elements by the given fields.
- near(longitude, latitude, radius_km=None)[source]
Find elements near given coordinates.
- within_bounds(north, south, east, west)[source]
Find elements within a bounding box.
- has_coordinates()[source]
Find elements that have coordinate data.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]- Returns:
QuerySet with elements having coordinates
- valid_coordinates()[source]
Find elements with valid coordinate ranges.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]- Returns:
QuerySet with valid coordinates
- add(*elements)[source]
Add elements to this manager.
- remove(*elements)[source]
Remove elements from this manager.
- create(**kwargs)[source]
Create a new element and add it to this manager.
- get_or_create(**kwargs)[source]
Get an existing element or create a new one.
- class kmlorm.core.managers.FolderManager(folders_manager=None)[source]
Bases:
KMLManager[Folder]Manager class for handling Folder model instances within the KML ORM framework.
This class extends KMLManager to provide specialized management for Folder objects, including creation and model class resolution.
- create(**kwargs)[source]
Creates and returns a new instance of the Folder model using the provided keyword arguments.
This method ensures the model class is set before delegating the creation process to the parent class.
- Parameters:
**kwargs (Any) – Arbitrary keyword arguments representing the fields and values for
instance. (the new Folder)
- Returns:
The newly created Folder instance.
- Return type:
Folder
- class kmlorm.core.managers.PlacemarkManager(folders_manager=None)[source]
Bases:
KMLManager[Placemark]Manager class for handling Placemark objects within a KML structure.
This class provides methods to create and manage Placemark instances, optionally associating them with a Folders manager. It ensures the correct model class is set before performing operations.
- create(**kwargs)[source]
Creates a new Placemark instance with the given keyword arguments and adds it to the manager.
- Parameters:
**kwargs (Any) – Arbitrary keyword arguments used to initialize the Placemark instance.
- Returns:
The newly created Placemark object.
- Return type:
Placemark
- class kmlorm.core.managers.PathManager(folders_manager=None)[source]
Bases:
KMLManager[Path]Manager class for handling operations related to the ‘Path’ model.
This class extends KMLManager to provide specialized management for ‘Path’ objects, including creation and model class setup.
- create(**kwargs)[source]
Creates a new instance of the Path model with the provided keyword arguments and adds it to the manager.
- Parameters:
**kwargs (Any) – Arbitrary keyword arguments corresponding to the fields of the Path model.
- Returns:
The newly created Path instance.
- Return type:
Path
- class kmlorm.core.managers.PolygonManager(folders_manager=None)[source]
Bases:
KMLManager[Polygon]Manager class for handling Polygon model instances within the KML ORM framework.
This class extends KMLManager to provide specialized management for Polygon objects, including creation and association with optional Folder managers.
- create(**kwargs)[source]
Creates and returns a new instance of the Polygon model using the provided keyword arguments.
This method ensures the model class is set before delegating the creation process to the superclass.
- Parameters:
**kwargs (Any) – Arbitrary keyword arguments corresponding to the Polygon model fields.
- Returns:
The newly created Polygon instance.
- Return type:
Polygon
- class kmlorm.core.managers.PointManager(folders_manager=None)[source]
Bases:
KMLManager[Point]Manager class for handling Point model instances within the KML ORM framework.
This class extends KMLManager to provide specialized management for Point objects, including creation and model class resolution.
- create(**kwargs)[source]
Creates a new Point instance with the given keyword arguments and adds it to the manager.
- Parameters:
**kwargs (Any) – Arbitrary keyword arguments used to initialize the Point instance.
- Returns:
The newly created Point object.
- Return type:
Point
- class kmlorm.core.managers.MultiGeometryManager(folders_manager=None)[source]
Bases:
KMLManager[MultiGeometry]Manager class for handling MultiGeometry objects within the KML ORM framework.
This class extends KMLManager to provide specialized management for MultiGeometry instances, including creation and model class resolution.
- create(**kwargs)[source]
- Creates a new MultiGeometry instance with the given keyword arguments and
adds it to the manager.
- Parameters:
**kwargs (Any) – Arbitrary keyword arguments used to initialize the MultiGeometry instance.
- Returns:
The newly created MultiGeometry object.
- Return type:
MultiGeometry
- class kmlorm.core.managers.RelatedManager(parent=None, related_name='')[source]
Bases:
KMLManager[T]Manager for related objects (e.g., folder.placemarks).
Extends KMLManager with relationship-specific functionality for managing collections of related KML elements.
- __init__(parent=None, related_name='')[source]
Initialize a RelatedManager.
- add(*elements)[source]
Add elements to this relationship.
- remove(*elements)[source]
Remove elements from this relationship.
- class kmlorm.core.managers.FolderRelatedManager(parent=None, related_name='')[source]
Bases:
RelatedManager[Folder]Manager for handling operations related to Folder model relationships.
This class extends RelatedManager to provide additional functionality or customization for managing related Folder instances.
- create(**kwargs)[source]
Creates a new Folder instance with the given keyword arguments and adds it to the manager.
- Parameters:
**kwargs (Any) – Arbitrary keyword arguments used to initialize the Folder instance.
- Returns:
The newly created Folder object.
- Return type:
Folder
- class kmlorm.core.managers.PlacemarkRelatedManager(parent=None, related_name='')[source]
Bases:
RelatedManager[Placemark]Manager for handling related Placemark objects.
This class extends the RelatedManager specifically for Placemark instances, providing an interface to manage and query related Placemark objects within the ORM context.
- create(**kwargs)[source]
Creates a new Placemark instance with the given keyword arguments and adds it to the manager.
- Parameters:
**kwargs (Any) – Arbitrary keyword arguments used to initialize the Placemark instance.
- Returns:
The newly created Placemark object.
- Return type:
Placemark
- class kmlorm.core.managers.PathRelatedManager(parent=None, related_name='')[source]
Bases:
RelatedManager[Path]A specialized RelatedManager for handling relationships involving the Path model.
This manager provides custom query and management capabilities for related Path objects.
- create(**kwargs)[source]
Creates a new Path instance with the given keyword arguments and adds it to the manager.
- Parameters:
**kwargs (Any) – Arbitrary keyword arguments used to initialize the Path instance.
- Returns:
The newly created Path object.
- Return type:
Path
- class kmlorm.core.managers.PolygonRelatedManager(parent=None, related_name='')[source]
Bases:
RelatedManager[Polygon]Manager for handling relationships and queries related to the Polygon model.
This class extends RelatedManager specifically for Polygon instances, enabling custom query and relationship management for polygons within the ORM.
- create(**kwargs)[source]
Creates a new Polygon instance with the given keyword arguments and adds it to the manager.
- Parameters:
**kwargs (Any) – Arbitrary keyword arguments used to initialize the Polygon instance.
- Returns:
The newly created Polygon object.
- Return type:
Polygon
- class kmlorm.core.managers.PointRelatedManager(parent=None, related_name='')[source]
Bases:
RelatedManager[Point]A specialized RelatedManager for handling relationships involving Point objects.
This manager provides an interface for managing and querying related Point instances within the ORM.
- create(**kwargs)[source]
Creates a new Point instance with the given keyword arguments and adds it to the manager.
- Parameters:
**kwargs (Any) – Arbitrary keyword arguments used to initialize the Point instance.
- Returns:
The newly created Point object.
- Return type:
Point
- class kmlorm.core.managers.MultiGeometryRelatedManager(parent=None, related_name='')[source]
Bases:
RelatedManager[MultiGeometry]Manager for handling related objects of the MultiGeometry model.
This class extends the generic RelatedManager to provide relationship management functionality specifically for MultiGeometry instances.
- create(**kwargs)[source]
Creates a new MultiGeometry instance with the given keyword arguments and adds it to the manager.
- Parameters:
**kwargs (Any) – Arbitrary keyword arguments used to initialize the MultiGeometry instance.
- Returns:
The newly created MultiGeometry object.
- Return type:
MultiGeometry
Core Query Methods
Basic Retrieval
- KMLQuerySet.all()[source]
Return a copy of this QuerySet.
This method exists for Django compatibility and returns a new QuerySet with the same elements.
- Return type:
KMLQuerySet[TypeVar(T, bound= KMLElement)]
- KMLQuerySet.filter(**kwargs)[source]
Filter elements based on field lookups.
Supports Django-style field lookups like: - name__icontains=’capital’ - coordinates__latitude__gte=39.0 - visibility=True
- KMLQuerySet.exclude(**kwargs)[source]
Exclude elements that match the given filters.
This is the inverse of filter() - returns elements that do NOT match the criteria.
- KMLQuerySet.get(**kwargs)[source]
Get a single element that matches the given criteria.
- Parameters:
**kwargs (
Any) – Field lookup expressions- Return type:
TypeVar(T, bound= KMLElement)- Returns:
Single matching KML element
- Raises:
KMLElementNotFound – If no elements match
KMLMultipleElementsReturned – If multiple elements match
Ordering and Slicing
- KMLQuerySet.order_by(*fields)[source]
Order elements by the given fields.
Supports field names with optional ‘-’ prefix for descending order.
Geospatial Methods
Distance-Based Queries
Bounding Box Queries
Coordinate Filtering
Distance Calculation Details
Understanding Geospatial Accuracy
KML ORM uses the Haversine formula to calculate great circle distances on Earth’s surface. This provides reliable distance calculations for most geospatial applications.
Technical Implementation:
Formula: Standard Haversine formula for great circle distances
Earth Radius: 6371 km (mean radius of Earth)
Coordinate System: WGS84 longitude/latitude in decimal degrees
Accuracy: Within 0.5% for distances up to hundreds of kilometers
Accuracy Characteristics:
# Example: 1 degree of latitude ≈ 111.32 km anywhere on Earth
# 1 degree of longitude ≈ 111.32 km * cos(latitude)
from kmlorm import KMLFile
kml = KMLFile.from_file('places.kml')
# Distance queries are accurate for typical use cases:
nearby_stores = kml.placemarks.near(-76.6, 39.3, radius_km=25) # ±125m accuracy
regional_search = kml.placemarks.near(-76.6, 39.3, radius_km=100) # ±500m accuracy
Limitations and Considerations:
Spherical Earth Assumption: Uses mean Earth radius rather than accounting for ellipsoidal shape
2D Calculations: Altitude/elevation is not considered in distance calculations
Great Circle Distance: Calculates “as the crow flies” distance, not driving/walking routes
Coordinate Precision: Limited by the precision of coordinates in your KML data
Recommended Use Cases:
Excellent for: Regional searches, proximity analysis, geographic clustering
Good for: City-scale analysis, finding nearby points of interest
Consider alternatives for: Sub-meter precision requirements, elevation-dependent calculations
Performance Notes:
Distance calculations are performed in-memory after loading the KML data. For large datasets with frequent geospatial queries, consider pre-filtering with bounding boxes before applying distance-based filters.
Query Examples
Basic Filtering
from kmlorm import KMLFile
kml = KMLFile.from_file('places.kml')
# Get all placemarks
all_places = kml.placemarks.all()
# Filter by name
capital_stores = kml.placemarks.filter(name__icontains='capital')
# Exclude certain items
not_capital = kml.placemarks.exclude(name__icontains='capital')
# Get single item
rosedale_store = kml.placemarks.get(name__contains='Rosedale')
Geospatial Queries
# Find placemarks near Baltimore
nearby = kml.placemarks.near(-76.6, 39.3, radius_km=25)
# Find placemarks within bounding box
in_area = kml.placemarks.within_bounds(
north=39.5, south=39.0,
east=-76.0, west=-77.0
)
# Only placemarks with coordinates
with_location = kml.placemarks.has_coordinates()
Chaining Queries
# Complex query chain
result = (kml.placemarks
.filter(name__icontains='electric')
.near(-76.6, 39.3, radius_km=50)
.has_coordinates()
.order_by('name')
)
Field Lookups
KML ORM supports Django-style field lookups:
exact- Exact match (default)icontains- Case-insensitive containscontains- Case-sensitive containsstartswith- Starts withendswith- Ends within- Value in listisnull- Is null/Noneregex- Regular expression match
# Various lookup examples
kml.placemarks.filter(name='Capital Electric') # exact
kml.placemarks.filter(name__icontains='capital') # case-insensitive
kml.placemarks.filter(name__startswith='Capital') # starts with
kml.placemarks.filter(coordinates__isnull=False) # has coordinates