Documentation for python-stdnet's DEVELOPMENT version. Get the release docs here.

Fields API

The most important part of a model, and the only required part of a model, is the list of database fields it defines. Fields are specified by class attributes. They are the equivalent to django Fields and therefore the equivalent of columns in a traditional relational databases.


There is an important difference between stdnet fields and fields in a traditional relational database. Stdnet fields can be added, removed or changed without requiring any time consuming database migration!

This is an added bonus which can be of high importance when prototyping.

Base Classes

The Field class is the base class for all fields and contains all the attribute and method definitions. Derived classes only implement a handful of methods.


class stdnet.odm.Field(unique=False, primary_key=False, required=True, index=None, hidden=None, as_cache=False, **extras)

This is the base class of all StdNet Fields. Each field is specified as a StdModel class attribute.


Probably the most important field attribute, it establish if the field creates indexes for queries. If you don’t need to query the field you should set this value to False, it will save you memory.


if index is set to False executing queries against the field will throw a stdnet.QuerySetError exception. No database queries are allowed for non indexed fields as a design decision (explicit better than implicit).

Default True.


If True, the field must be unique throughout the model. In this case Field.index is also True. Enforced at stdnet.BackendDataServer level.

Default False.


If True, this field is the primary key for the model. A primary key field has the following properties:

  • Field.unique is also True.
  • There can be only one in a model.
  • It’s attribute name in the model must be id.
  • If not specified a AutoIdField will be added.

Default False.


If False, the field is allowed to be null.

Default True.


Default value for this field. It can be a callable attribute with arity 0.

Default None.


Field name, created by the odm at runtime.


The attribute name for the field, created by the get_attname() method at runtime. For most field, its value is the same as the name. It is the field sorted in the backend database.


The StdModel holding the field. Created by the odm at runtime.


The charset used for encoding decoding text.


If True the field will be hidden from search algorithms.

Default False.


The python type for the Field.


If True the field contains data which is considered cache and therefore always reproducible. Field marked as cache, have required always False.

This attribute is used by the StdModel.fieldvalue_pairs method which returns a dictionary of field names and values.

Default False.

register_with_model(name, model)

Called during the creation of a the StdModel class when Metaclass is initialised. It fills and Field.model. This is an internal function users should never call.


Add this Field to the fields of model.


Generate the attname at runtime


name for the private attribute which contains a cached value for this field. Used only by realted fields.


Field id for object obj, if applicable. Default is None.


Returns the default value for this field.

get_lookup(remaining, errorClass=<class 'ValueError'>)

called by the Query method when it needs to build lookup on fields with additional nested fields. This is the case of ForeignKey and JSONField.

  • remaining – the double underscored fields if this Field
  • errorClass – Optional exception class to use if the remaining field is not valid.
get_value(instance, *bits)

Retrieve the value Field from a StdModel instance.

  • instance – The StdModel instance invoking this function.
  • bits – Additional information for nested fields which derives from the double underscore notation.

the value of this Field in the instance. can raise AttributeError.

This method is used by the StdModel.get_attr_value() method when retrieving values form a StdModel instance.

set_value(instance, value)

Set the value for this Field in a instance of a StdModel.

set_get_value(instance, value)

Set the value for this Field in a instance of a StdModel and return the database representation. This method is invoked by the validation lagorithm before saving instances.

to_python(value, backend=None)

Converts the input value into the expected Python data type, raising stdnet.FieldValueError if the data can’t be converted. Returns the converted value. Subclasses should override this.

serialise(value, lookup=None)

Convert value to a valid database representation for this field.

This method is invoked by the Query algorithm.


Return a representation of this field which is compatible with JSON.


Function which evaluate a score from the field value. Used by the ordering alorithm


class stdnet.odm.AtomField(unique=False, primary_key=False, required=True, index=None, hidden=None, as_cache=False, **extras)

The base class for fields containing atoms. An atom is an irreducible value with a specific data type. it can be of four different types:

  • boolean
  • integer
  • date
  • datetime
  • floating point
  • symbol


class stdnet.odm.StructureField(model=None, pickler=None, value_pickler=None, class_field=False, **kwargs)

Virtual base class for Field which are proxies to data structures such as List, Set, Zset, HashTable and timeseries TS.

Sometimes you want to structure your data model without breaking it up into multiple entities. For example, you might want to define model that contains a list of messages an instance receive:

from stdnet import orm

class MyModel(odm.StdModel):
    messages = odm.ListField()

By defining structured fields in a model, an instance of that model can access a stand alone structure in the back-end server with very little effort:

m = MyModel.objects.get(id=1)
m.messages.push_back('Hello there!')

Behind the scenes, this functionality is implemented by Python descriptors.

Parameters:model – an optional StdModel class. If specified, the structured will contains ids of instances of the model and it can be accessed via the relmodel attribute. It can also be specified as a string if class specification is not possible.

Additional Field attributes


Optional StdModel class contained in the structure.


An stdnet.utils.encoders.Encoder used to encode and decode values.

Default: stdnet.utils.encoders.Json.


Same as the value_pickler attribute, this serializer is applied to keys, rather than values, in StructureField of PairMixin type (these include HashField, TimeSeriesField and ordered SetField)

Default: None.


If True this StructureField is a class field (it belongs to the model class rather than model instances). For example:

class MyModel(odm.StdModel):
    updates = odm.List(class_field=True)


Default: False.


Returns the Structure class for this field.

Atom Fields

Atom Fields derived from AtomField and, as the name says, they represent the simplest data in a model. Their representation in python, is one of bytes, strings, numbers or dates.


class stdnet.odm.IntegerField(unique=False, primary_key=False, required=True, index=None, hidden=None, as_cache=False, **extras)

An integer AtomField.


alias of int


class stdnet.odm.BooleanField(required=False, **kwargs)

A boolean AtomField


alias of bool


class stdnet.odm.AutoIdField(*args, **kwargs)

An AtomField for primary keys which are automatically generated by the backend server. You usually won’t need to use this directly; a primary_key field of this type, named id, will automatically be added to your model if you don’t specify otherwise. Check the primary key tutorial for further information on primary keys.


class stdnet.odm.FloatField(unique=False, primary_key=False, required=True, index=None, hidden=None, as_cache=False, **extras)

An floating point AtomField. By default its Field.index is set to False.


alias of float


class stdnet.odm.SymbolField(unique=False, primary_key=False, required=True, index=None, hidden=None, as_cache=False, **extras)

An AtomField which contains a symbol. A symbol holds a unicode string as a single unit. A symbol is irreducible, and are often used to hold names, codes or other entities. They are indexes by default.


alias of str


class stdnet.odm.CharField(*args, **kwargs)

A text SymbolField which is never an index. It contains unicode and by default and Field.required is set to False.


class stdnet.odm.ByteField(*args, **kwargs)

A CharField which contains binary data. In python this is converted to bytes.


alias of bytes


class stdnet.odm.DateField(unique=False, primary_key=False, required=True, index=None, hidden=None, as_cache=False, **extras)

An AtomField represented in Python by a instance.


alias of date


class stdnet.odm.DateTimeField(unique=False, primary_key=False, required=True, index=None, hidden=None, as_cache=False, **extras)

A date AtomField represented in Python by a datetime.datetime instance.


alias of datetime


class stdnet.odm.CompositeIdField(*fields, **kwargs)

This field can be used when an instance of a model is uniquely identified by a combination of two or more Field in the model itself. It requires a number of positional arguments greater or equal 2. These arguments must be fields names in the model where the CompositeIdField is defined.


list of Field names which are used to uniquely identify a model instance

Check the composite id tutorial for more information and tips on how to use it.

Object Type Fields


class stdnet.odm.JSONField(*args, **kwargs)

A JSON field which implements automatic conversion to and from an object and a JSON string. It is the responsability of the user making sure the object is JSON serializable.

There are few extra parameters which can be used to customize the behaviour and how the field is stored in the back-end server.


A boolean indicating if data should be serialized into a single JSON string or it should be used to create several fields prefixed with the field name and the double underscore __.

Default True.

Effectively, a JSONField with as_string attribute set to False is a multifield, in the sense that it generates several field-value pairs. For example, lets consider the following:

class MyModel(odm.StdModel):
    name = odm.SymbolField()
    data = odm.JSONField(as_string=False)


>>> m = MyModel(name='bla',
...             data={'pv': {'': 0.5, 'mean': 1, 'std': 3.5}})
>>> m.cleaned_data
{'name': 'bla', 'data__pv': 0.5, 'data__pv__mean': '1',
 'data__pv__std': '3.5', 'data': '""'}

The reason for setting as_string to False is to allow the JSONField to define several fields at runtime, without introducing new Field in your model class. These fields behave exactly like standard fields and therefore you can, for example, sort queries with respect to them:

>>> MyModel.objects.query().sort_by('data__pv__std')
>>> MyModel.objects.query().sort_by('-data__pv')

which can be rather useful feature.


class stdnet.odm.PickleObjectField(*args, **kwargs)

A field which implements automatic conversion to and form a picklable python object. This field is python specific and therefore not of much use if accessed from external programs. Consider the ForeignKey or JSONField fields as more general alternatives.


The best way to use this field is when its Field.as_cache attribute is True.


class stdnet.odm.ModelField(unique=False, primary_key=False, required=True, index=None, hidden=None, as_cache=False, **extras)

A filed which can be used to store the model classes (not only StdModel models). If a class has a attribute _meta with a unique hash attribute hash and it is registered in the model hash table, it can be used.

Data-structure Fields

These fields are remote data-structures such as list, sets and hash tables which are bound to a StdModel. All the data-structure fields derives from StructureField. These fields can be either bound to StdModel instance (default) or class via the StructureField.class_field flag.


class stdnet.odm.ListField(model=None, pickler=None, value_pickler=None, class_field=False, **kwargs)

A field maintaining a list of values.

When accessed from the model instance, it returns a of List structure. For example:

class UserMessage(odm.StdModel):
    user = odm.SymbolField()
    messages = odm.ListField()

Lets register it with redis:

>>> odm.register(UserMessage, "redis://")
'redis db 7 on'

Can be used as:

>>> m = UserMessage(user='pippo').save()
>>> m.messages.push_back("adding my first message to the list")
>>> m.messages.push_back("ciao")
>>> type(u.messages)
<class 'stdnet.odm.struct.List'>
>>> u.messages.size()


class stdnet.odm.SetField(*args, **kwargs)

A field maintaining an unordered or ordered collection of values. It is initiated without any argument other than an optional model class:

class User(odm.StdModel):
    username  = odm.AtomField(unique = True)
    password  = odm.AtomField()
    following = odm.SetField(model = 'self')

It can be used in the following way:

>>> user = User(username='lsbardel', password='mypassword').save()
>>> user2 = User(username='pippo', password='pippopassword').save()
>>> user.following.add(user2)
>>> user2 in user.following

A flag indicating if the elements in this set are ordered with respect a score. If ordered, the StructureField.structure_class() method returns a Zset otherwise a Set. Default False.


class stdnet.odm.HashField(model=None, pickler=None, value_pickler=None, class_field=False, **kwargs)

A Hash table field, the networked equivalent of a python dictionary. Keys are string while values are string/numeric. it returns an instance of HashTable structure.


class stdnet.odm.TimeSeriesField(model=None, pickler=None, value_pickler=None, class_field=False, **kwargs)

A timeseries field based on TS data structure.


class stdnet.odm.LazyForeignKey(field)

Descriptor for a ForeignKey field.

class stdnet.odm.StructureFieldProxy(field, factory)

A descriptor for a StructureField.