This code defines a class `Shipment` using SQLAlchemy, an object-relational...
This code defines a class Shipment
using SQLAlchemy, an object-relational mapping (ORM) library in Python, for interacting with a relational database. Here's what the code does in detail:
-
Maps to a Database Table:
- The class name
Shipment
represents a table named"shipments"
in the database, defined by__tablename__ = "shipments"
.
- The class name
-
Defines Columns: Each attribute in the class represents a column in the database table, with specific constraints and types.
id
: Primary key, an integer column that uniquely identifies each shipment. It is also indexed for faster retrieval.shipment_number
: A unique identifier for the shipment (up to 50 characters), cannot be null.contract_id
andagency_id
: Foreign keys referencing thecontract
andagency
tables respectively ("contract.id"
and"agency.id"
).- Other columns like
vessel_name
,voyage_number
,cargo_type
, and others store shipment details such as vessel information, cargo, ports, dates, and status. - Fields like
created_at
andupdated_at
automatically store the timestamp for creation and updates usingfunc.now()
. created_by
andassigned_to
: Foreign keys pointing to ausers
table to store which user created or was assigned the shipment.
-
Relationships between Tables: Relationships establish links between the
Shipment
table and other tables:contract
: A relationship to theContract
table (uses theshipments
attribute in theContract
class for back-population).agency
: A relationship to theAgency
table (uses theshipments
attribute in theAgency
class for back-population).creator
andassignee
: Relationships to theUser
table, linking shipments to the user who created or was assigned to the shipment.transactions
: A one-to-many or many-to-many relationship to theFinancialTransaction
table for related transactions.
-
Constraints and Defaults:
- Sets constraints like
nullable=False
to ensure required fields (shipment_number
) cannot be left empty. - Includes defaults for columns like
status
(planned
) and auto-updating timestamps withonupdate
.
- Sets constraints like
-
Data Types:
- Uses various SQLAlchemy column types such as
String
for text,Text
for larger text,Integer
for numbers,Numeric
for decimal numbers with precision,Date
for dates, andDateTime
for time-stamped fields.
- Uses various SQLAlchemy column types such as
In summary, this class represents a shipment record in the database, complete with its fields, constraints, relationships, and other metadata for ORM mapping. It allows you to query associated contracts, users, agencies, and financial transactions in a relational and programmatic way.