Alias is a proxy to another field, potentially nested, within the same document.
Alias allows class-level querying and instance-level read access, write access under most conditions, as well as optional deprecation warning generation.
from marrow.mongo.field import Alias
This pseudo-field does not inherit other field attributes.
A string reference to another field in the same containing class. See the Usage section below for the structure of these references.
Used to determine if access should issue
DeprecationWarning messages. If truthy, a warning will be raised, and if non-boolean the string value will be included in the message.
Instantiate and assign an instance of this class during construction of a new
Document subclass, passing the attributes in as positional (in the order seen above) or keyword arguments. This pseudo-field utilizes the Marrow Package
traverse utility to allow it to resolve a wide variety of attributes.
References to other fields may be:
The string name of a sibling attribute.
The path to a descendant attribute of a sibling.
Or involving numeric array indexes.
Or involving dictionary key references.
Paths are strings comprised of dot-separated attribute names. The search beings at the containing document, consuming path elements as we go. Each path element is first attempted as an attribute and, failing that, will attempt dictionary access. If the path element is numeric, it will be utilized as an array index.
Alias at the class level will resolve a Queryable for the target field, allowing filter document construction through comparison utilizing the
alias name itself. On an instance access will retrieve or assign the value of the target field.
As it might not be natural to refer to the user's username everywhere as
id, especially if dereferenced from a variable, you can use an
Alias to provide a more contextual name for the identifier.
class User(Document):id = String('_id')username = Alias('id')User.find_many(username__startswith="a")
There are situations where elevating an embedded value can be useful to, for example, shorten frequent queries or variable references in templates.
class Package(Document):class Address(Document):city = String()...address = Embed(Address, assign=True)city = Alias('address.city')
If you're savvy and always insert the most recent message at the beginning of the unread messages array, you can easily and semantically access the latest message using an
class Conversation(Document):class Message(Document):id = ObjectId('_id')sender = Field()message = Field()messages = Array(Embed(Message), assign=True)latest = Alias('messages.0')
Data modelling requirements change over time and there can be a lot of code referencing a given document attribute. Help identify where that access is coming from by marking old, deprecated attributes using
Alias with an appropriate message.
class User(Document):id = String('_id')username = Alias('id',deprecate="Username is now primary key.")