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

Primary Keys and Unique Fields

Each StdModel must have a primary key. The model primary key Field can be obtained via the StdModel.pk() class method. A model can have one and only one primary key which is specified by passing primary_key=True during model definition:

class MyModel(odm.StdModel):
    id = odm.SymbolField(primary_key=True)
    ...

A primary key field has the Field.primary_key attribute True.

Composite ID

The CompositeIdField enforces a group of fields in a model to be unique (together). Let`s consider the following model:

class Vote(StdModel):
    full_name = odm.SymbolField()
    address = odm.SymbolField()
    result = odm.SymbolField()

Now I want to make full_name and address unique together, so that given a name and address I can uniquely identify a vote. This is achieved by introducing a CompositeIdField:

class Vote(StdModel):
    id = odm.CompositeIdField('full_name', 'address')
    full_name = odm.SymbolField()
    address = odm.SymbolField()
    result = odm.SymbolField()

Note

The CompositeIdField is used, behind the scenes, by the through model in the ManyToManyField.

Unique Fields

A Field can be enforced to be unique by passing the unique=True during model definition. The following models specifies two fields to be unique across the whole model instances:

class MyModel(odm.StdModel):
    full_name = odm.SymbolField()
    username = odm.SymbolField(unique=True)
    email = odm.SymbolField(unique=True)

Table Of Contents

Previous topic

Field Generator

Next topic

Performance

This Page