Peewee - Field Class



Model class contains one or more attributes that are objects of Field class in Peewee. Base Field class is not directly instantiated. Peewee defines different sub classes for equivalent SQL data types.

Constructor of Field class has following parameters−

Sr.No Constructor & Description
1

column_name (str)

Specify column name for field.

2

primary_key (bool)

Field is the primary key.

3

constraints (list)

List of constraints to apply to column

4

choices (list)

An iterable of 2-tuples mapping column values to display labels.

5

null (bool)

Field allows NULLs.

6

index (bool)

Create an index on field.

7

unique (bool)

Create an unique index on field.

8

Default

Default value.

9

collation (str)

Collation name for field.

10

help_text (str)

Help-text for field, metadata purposes.

11

verbose_name (str)

Verbose name for field, metadata purposes.

Subclasses of Field class are mapped to corresponding data types in various databases, i.e. SQLite, PostgreSQL, MySQL, etc.

Numeric Field classes

The numeric field classes in Peewee are given below −

Sr.No Field classes & Description
1

IntegerField

Field class for storing integers.

2

BigIntegerField

Field class for storing big integers (maps to integer, bigint, and bigint type in SQLite, PostegreSQL and MySQL respectively).

3

SmallIntegerField

Field class for storing small integers (if supported by database).

4

FloatField

Field class for storing floating-point numbers corresponds to real data types.

5

DoubleField

Field class for storing double-precision floating-point numbers maps to equivalent data types in corresponding SQL databases.

6

DecimalField

Field class for storing decimal numbers. The parameters are mentioned below −

  • max_digits (int) – Maximum digits to store.

  • decimal_places (int) – Maximum precision.

  • auto_round (bool) – Automatically round values.

Text fields

The text fields which are available in Peewee are as follows −

Sr.No Fields & Description
1

CharField

Field class for storing strings. Max 255 characters. Equivalent SQL data type is varchar.

2

FixedCharField

Field class for storing fixed-length strings.

3

TextField

Field class for storing text. Maps to TEXT data type in SQLite and PostgreSQL, and longtext in MySQL.

Binary fields

The binary fields in Peewee are explained below −

Sr.No Fields & Description
1

BlobField

Field class for storing binary data.

2

BitField

Field class for storing options in a 64-bit integer column.

3

BigBitField

Field class for storing arbitrarily-large bitmaps in a Binary Large OBject (BLOB). The field will grow the underlying buffer as necessary.

4

UUIDField

Field class for storing universally unique identifier (UUID) objects. Maps to UUID type in Postgres. SQLite and MySQL do not have a UUID type, it is stored as a VARCHAR.

Date and Time fields

The date and time fields in Peewee are as follows −

Sr.No Fields & Description
1

DateTimeField

Field class for storing datetime.datetime objects. Accepts a special parameter string formats, with which the datetime can be encoded.

2

DateField

Field class for storing datetime.date objects. Accepts a special parameter string formats to encode date.

3

TimeField

Field class for storing datetime.time objectsAccepts a special parameter formats to show encoded time.

Since SQLite doesn’t have DateTime data types, this field is mapped as string.

ForeignKeyField

This class is used to establish foreign key relationship in two models and hence, the respective tables in database. This class in instantiated with following parameters −

Sr.No Fields & Description
1

model (Model)

Model to reference. If set to ‘self’, it is a self-referential foreign key.

2

field (Field)

Field to reference on model (default is primary key).

3

backref (str)

Accessor name for back-reference. “+” disables the back-reference accessor.

4

on_delete (str)

ON DELETE action.

5

on_update (str)

ON UPDATE action.

6

lazy_load (bool)

Fetch the related object, when the foreign-key field attribute is accessed. If FALSE, accessing the foreign-key field will return the value stored in the foreign-key column.

Example

Here is an example of ForeignKeyField.

from peewee import *

db = SqliteDatabase('mydatabase.db')
class Customer(Model):
   id=IntegerField(primary_key=True)
   name = TextField()
   address = TextField()
   phone = IntegerField()
   class Meta:
      database=db
      db_table='Customers'

class Invoice(Model):
   id=IntegerField(primary_key=True)
   invno=IntegerField()
   amount=IntegerField()
   custid=ForeignKeyField(Customer, backref='Invoices')
   class Meta:
      database=db
      db_table='Invoices'

db.create_tables([Customer, Invoice])

When above script is executed, following SQL queries are run −

CREATE TABLE Customers (
   id INTEGER NOT NULL
   PRIMARY KEY,
   name TEXT NOT NULL,
   address TEXT NOT NULL,
   phone INTEGER NOT NULL
);
CREATE TABLE Invoices (
   id INTEGER NOT NULL
   PRIMARY KEY,
   invno INTEGER NOT NULL,
   amount INTEGER NOT NULL,
   custid_id INTEGER NOT NULL,
   FOREIGN KEY (
      custid_id
   )
   REFERENCES Customers (id)
);

When verified in SQLiteStuidio GUI tool, the table structure appears as below −

ForeignKey Field SQLite Stuidio GUI Tool

Other Field Types

The other field types in Peewee include −

Sr.No Fields & Description
1

IPField

Field class for storing IPv4 addresses efficiently (as integers).

2

BooleanField

Field class for storing boolean values.

3

AutoField

Field class for storing auto-incrementing primary keys.

4

IdentityField

Field class for storing auto-incrementing primary keys using the new Postgres 10 IDENTITYField class for storing auto-incrementing primary keys using the new Postgres 10 IDENTITY column type. column type.

Advertisements