Fields — peewee 0.8.0 documentation

### Navigation

- index
- next |
- previous |
- peewee 0.8.0 documentation »

# Fields

The `Field` class is used to describe the mapping of `Model` attributes to database columns. Each field type has a corresponding SQL storage class (i.e. varchar, int), and conversion between python data types and underlying storage is handled transparently.

When creating a `Model` class, fields are defined as class-level attributes. This should look familiar to users of the django framework. Here’s an example:

    from peewee import *

    class User(Model):
        username = CharField()
        join_date = DateTimeField()
        about_me = TextField()

There is one special type of field, `ForeignKeyField`, which allows you to expose foreign-key relationships between models in an intuitive way:

    class Message(Model):
        user = ForeignKeyField(User, related_name='messages')
        body = TextField()
        send_date = DateTimeField()

This allows you to write code like the following:

    >>> print some_message.user.username
    Some User

    >>> for message in some_user.messages:
    ...     print message.body
    some message
    another message
    yet another message

## Field types table

Parameters accepted by all field types and their default values:

- `null = False` – boolean indicating whether null values are allowed to be stored
- `db_index = False` – boolean indicating whether to create an index on this column
- `unique = False` – boolean indicating whether to create a unique index on this column
- `verbose_name = None` – string representing the “user-friendly” name of this field
- `help_text = None` – string representing any helpful text for this field

Field Type | Sqlite | Postgresql | MySQL
--- | --- | --- | ---
`CharField` | varchar | varchar | varchar
`TextField` | text | text | longtext
`DateTimeField` | datetime | timestamp | datetime
`IntegerField` | integer | integer | integer
`BooleanField` | smallint | boolean | bool
`FloatField` | real | real | real
`DoubleField` | real | double precision | double precision
`BigIntegerField` | integer | bigint | bigint
`DecimalField` | decimal | numeric | numeric
`PrimaryKeyField` | integer | serial | integer
`ForeignKeyField` | integer | integer | integer

Field type | Special Parameters
--- | ---
`CharField` | `max_length`
`DecimalField` | `max_digits`, `places`
`ForeignKeyField` | `to`, `related_name`, `cascade`, `extra`

## Self-referential Foreign Keys

Since the class is not available at the time the field is declared, when creating a self-referential foreign key pass in ‘self’ as the “to” relation:

    class Category(Model):
        name = CharField()
        parent = ForeignKeyField('self', related_name='children', null=True)

## Field class API

class `Field`

  The base class from which all other field types extend.

  `__init__`(null=False, db_index=False, unique=False, verbose_name=None, help_text=None, *args, **kwargs)

    Parameters: | null – this column can accept `None` or `NULL` values db_index – create an index for this column when creating the table unique – create a unique index for this column when creating the table verbose_name – specify a “verbose name” for this field, useful for metadata purposes help_text – specify some instruction text for the usage/meaning of this field

  `db_value`(value)

    Parameters: | value – python data type to prep for storage in the database
    Return type: | converted python datatype

  `python_value`(value)

    Parameters: | value – data coming from the backend storage
    Return type: | python data type

  `lookup_value`(lookup_type, value)

    Parameters: | lookup_type – a peewee lookup type, such as ‘eq’ or ‘contains’ value – a python data type
    Return type: | data type converted for use when querying

  `class_prepared`()

    Simple hook for `Field` classes to indicate when the `Model` class the field exists on has been created.

class `CharField`

  Stores: small strings (0-255 bytes)

class `TextField`

  Stores: arbitrarily large strings

class `DateTimeField`

  Stores: python `datetime` instances

class `IntegerField`

  Stores: integers

class `BooleanField`

  Stores: `True` / `False`

class `FloatField`

  Stores: floating-point numbers

class `DecimalField`

  Stores: decimal numbers

class `PrimaryKeyField`

  Stores: auto-incrementing integer fields suitable for use as primary key

class `ForeignKeyField`

  Stores: relationship to another model

  `__init__`(to[, related_name=None[, ...]])

    Parameters: | to – related `Model` class or the string ‘self’ if declaring a self-referential foreign key related_name – attribute to expose on related model

        class Blog(Model):
            name = CharField()

        class Entry(Model):
            blog = ForeignKeyField(Blog, related_name='entries')
            title = CharField()
            content = TextField()

        # "blog" attribute
        >>> some_entry.blog
        <Blog: My Awesome Blog>

        # "entries" related name attribute
        >>> for entry in my_awesome_blog.entries:
        ...     print entry.title
        Some entry
        Another entry
        Yet another entry