Fields

The fields module defines various field classes all of which are derived from BaseField.

Field Methods

BaseField.validate(raw_data, **kwargs)[source]

The validate method validates raw_data against the field .

Parameters:raw_data (str or other valid formats) – raw data for field
Returns:validated_data
Raises ValidationException:
 if self.required and raw_data is None
BaseField.deserialize(raw_data, **kwargs)[source]
BaseField.serialize(py_data, **kwargs)[source]
class xmodels.fields.BaseField(**kwargs)[source]

Base class for all field types.

The source parameter sets the key that will be retrieved from the source data. If source is not specified, the field instance will use its own name as the key to retrieve the value from the source data.

The serial_format parameter controls the serialization format, e.g. in DateTimeField etc.

A default value can be assigned through the default parameter.

Parameters:
  • kwargs[‘required’] (bool) – indicates required field
  • kwargs[‘default’] (str) – default value, used when raw_data is None
  • kwargs[‘serial_format’] (str) – format string for serialization and deserialization
  • kwargs[‘source’] (str) – field name for serialized version
class xmodels.fields.RegexField(**kwargs)[source]

Field to represent unicode strings matching a regular expression. It raises ValidationException if there is no match. :param regex: regular expression to match.

class xmodels.fields.RangeField(**kwargs)[source]

Base class for IntegerField and FloatField. :param int/float kwargs[‘min’]: indicates minimum allow value (inclusive). :param int/float kwargs[‘max’]: indicates maximum allow value (inclusive).

Basic Fields

BooleanField

class xmodels.BooleanField(**kwargs)

Field to represent a boolean. The string 'True' (case insensitive) will be converted to True, as will any positive integers and the boolean value True.

>>> from xmodels import BooleanField
>>> BooleanField().validate('TRUE')
True
>>> BooleanField().validate('not true!')
False
>>> BooleanField().validate(42)
True
>>> BooleanField().validate(-3)
False
>>> BooleanField().validate(True)
True

CharField

class xmodels.CharField(**kwargs)

Field to represent a simple Unicode string value.

>>> from xmodels import CharField
>>> char_field = CharField()
>>> char_field.validate(' valid unicode string!\n')
'valid unicode string!'
class xmodels.Token(**kwargs)

CharField for xsd:token. Tokens are strings without leading and trailing whitespaces. All other whitespaces are collapsed.

class xmodels.Name(**kwargs)

Field for xsd:name. Values of this type must start with a letter, underscore (_), or colon (:), and may contain only letters, digits, underscores (_), colons (:), hyphens (-), and periods (.). Colons should only be used to separate namespace prefixes from local names.

>>> from xmodels import Name
>>> name_field = Name()
>>> name_field.validate('valid_name')
'valid_name'
class xmodels.NCName(**kwargs)

Field for xsd:ncname. The type NCName represents an XML non-colonized name, which is simply a name that does not contain colons. An NCName must start with either a letter or underscore (_) and may contain only letters, digits, underscores (_), hyphens (-), and periods (.). This is identical to the Name type, except that colons are not permitted.

class xmodels.Language(**kwargs)

Field for xsd:language. The type language represents a natural language identifier, generally used to indicate the language of a document or a part of a document. Before creating a new attribute of type language, consider using the xml:lang attribute that is intended to indicate the natural language of the element and its content. Values of the language type conform to RFC 3066, Tags for the Identification of Languages, in version 1.0 and to RFC 4646, Tags for Identifying Languages, and RFC 4647, Matching of Language Tags, in version 1.1. The three most common formats are: For ISO-recognized languages, the format is a two- or three-letter (usually lowercase) language code that conforms to ISO 639, optionally followed by a hyphen and a two-letter, usually uppercase, country code that conforms to ISO 3166. For example, en or en-US. For languages registered by the Internet Assigned Numbers Authority (IANA), the format is i-langname, where langname is the registered name. For example, i-navajo. For unofficial languages, the format is x-langname, where langname is a name of up to eight characters agreed upon by the two parties sharing the document. For example, x-Newspeak. Any of these three formats may have additional parts, each preceded by a hyphen, which identify more countries or dialects. Schema processors will not verify that values of the language type conform to the above rules. They will simply deserialize them based on the pattern specified for this type, which says that it must consist of one or more parts of up to eight characters each, separated by hyphens.

class xmodels.NMTOKEN(**kwargs)

Field for xsd:NMTOKEN. The type NMTOKEN represents a single string token. NMTOKEN values may consist of letters, digits, periods (.), hyphens (-), underscores (_), and colons (:). They may start with any of these characters. NMTOKEN has a whitespace facet value of collapse, so any leading or trailing whitespace will be removed. However, no whitespace may appear within the value itself.

class xmodels.IntegerField(**kwargs)

Field to represent an integer value.

class xmodels.NonNegativeInteger(**kwargs)

Field to represent a non negative integer value.

class xmodels.PositiveInteger(**kwargs)

Field to represent a positive integer value.

class xmodels.NegativeInteger(**kwargs)

Field to represent a negative integer value.

class xmodels.FloatField(**kwargs)

Field to represent a floating point value. The serial_format uses the standard string format notation with the surrounding curly brackets.

class xmodels.NonNegativeFloat(**kwargs)

Field to represent a non negative floating point value.

class xmodels.EnumField(**kwargs)

Tests that the value is one of the members of a given list (options). There can be no empty strings in options. value has to be a string.

If matchLower is True it will also compare value.lower() with the lower case version of all strings in options.

Datetime Fields

class xmodels.DateTimeField(**kwargs)

Field to represent a datetime

The format parameter dictates the format of the input strings, and is used in the construction of the datetime.datetime object.

The serial_format parameter is a strftime formatted string for serialization. If serial_format isn’t specified, an ISO formatted string will be returned by to_serial().

class xmodels.DateField(**kwargs)

Field to represent a datetime.date

class xmodels.TimeField(**kwargs)

Field to represent a datetime.time

Relationship Fields

class xmodels.ModelField(wrapped_class, **kwargs)

Field containing a model instance

Use this field when you wish to nest one object inside another. It takes a single required argument, which is the nested class. For example, given the following dictionary:

some_data = {
    'first_item': 'Some value',
    'second_item': {
        'nested_item': 'Some nested value',
    },
}

You could build the following classes (note that you have to define the inner nested models first):

class MyNestedModel(xmodels.Model):
    nested_item = xmodels.CharField()

class MyMainModel(xmodels.Model):
    first_item = xmodels.CharField()
    second_item = xmodels.ModelField(MyNestedModel)
class xmodels.ModelCollectionField(wrapped_class, **kwargs)

Field containing a list of model instances.

Use this field when your source data dictionary contains a list of dictionaries. It takes a single required argument, which is the name of the nested class that each item in the list should be converted to. For example:

some_data = {
    'list': [
        {'value': 'First value'},
        {'value': 'Second value'},
        {'value': 'Third value'},
    ]
}

class MyNestedModel(xmodels.Model):
    value = xmodels.CharField()

class MyMainModel(xmodels.Model):
    list = xmodels.ModelCollectionField(MyNestedModel)
class xmodels.FieldCollectionField(field_instance, **kwargs)

Field containing a list of the same type of fields.

The constructor takes an instance of the field.

Here are some examples:

data = {
            'legal_name': 'John Smith',
            'aliases': ['Larry', 'Mo', 'Curly']
}

class Person(Model):
    legal_name = CharField()
    aliases = FieldCollectionField(CharField())

p = Person(data)

And now a quick REPL session:: FIXME doctest

Here is a bit more complicated example involving args and kwargs:

data = {
            'name': 'San Andreas',
            'dates': ['1906-05-11', '1948-11-02', '1970-01-01']
}

class FaultLine(Model):
    name = CharField()
    earthquake_dates = FieldCollectionField(DateField('%Y-%m-%d',
                                            serial_format='%m-%d-%Y'),
                                            source='dates')

f = FaultLine(data)

Notice that source is passed to to the FieldCollectionField, not the DateField.

Let’s check out the resulting Model instance with the