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
Parameters accepted by all field types and their default values:
| Field type | Underlying storage | Special Parameters |
|---|---|---|
| CharField | varchar | max_length |
| TextField |
|
none |
| DateTimeField |
|
none |
| IntegerField | integer | none |
| BooleanField |
|
none |
| FloatField |
|
none |
| DecimalField |
|
max_digits, places |
| PrimaryKeyField |
|
none |
| ForeignKeyField | foreign key | to, related_name, cascade, extra |
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)
The base class from which all other field types extend.
| Parameters: |
|
|---|
| Parameters: | value – python data type to prep for storage in the database |
|---|---|
| Return type: | converted python datatype |
| Parameters: | value – data coming from the backend storage |
|---|---|
| Return type: | python data type |
| Parameters: |
|
|---|---|
| Return type: | data type converted for use when querying |
Stores: small strings (0-255 bytes)
Stores: arbitrarily large strings
Stores: python datetime instances
Stores: integers
Stores: True / False
Stores: floating-point numbers
Stores: decimal numbers
Stores: auto-incrementing integer fields suitable for use as primary key
Stores: relationship to another model
| Parameters: |
|
|---|
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