Declarative models¶
If you need to generate a declarative_model
from SQLAlchemy ORM type, you can simply call
Model.declarative()
. Example, User.declarative()
. This will automatically generate the
declarative model type for you.
import saffier
from saffier import Database, Registry
database = Database("sqlite:///db.sqlite")
models = Registry(database=database)
# Declare the Saffier model
class User(saffier.Model):
is_active = saffier.BooleanField(default=True)
first_name = saffier.CharField(max_length=50)
last_name = saffier.CharField(max_length=50)
email = saffier.EmailField(max_lengh=100)
password = saffier.CharField(max_length=1000)
class Meta:
registry = models
# Generate the declarative version
UserModelDeclarative = User.declarative()
Be mindful that when using a declarative model if you have a ForeignKey or
a OneToOneField, Saffier will generate a SQLAlchemy Relationship
for you automatically and append relation
at the end of the declared field.
Let us see an example.
import saffier
from saffier import Database, Registry
database = Database("sqlite:///db.sqlite")
models = Registry(database=database)
class User(saffier.Model):
is_active = saffier.BooleanField(default=True)
first_name = saffier.CharField(max_length=50)
last_name = saffier.CharField(max_length=50)
email = saffier.EmailField(max_lengh=100)
password = saffier.CharField(max_length=1000)
class Meta:
registry = models
class Thread(saffier.Model):
sender = saffier.ForeignKey(
User,
on_delete=saffier.CASCADE,
related_name="sender",
)
receiver = saffier.ForeignKey(
User,
on_delete=saffier.CASCADE,
related_name="receiver",
)
message = saffier.TextField()
class Meta:
registry = models
As you can see, the model Thread
has two foreign keys, sender
and receiver
. In a normal
Saffier ORM operation, this remains as is but if you generate the declarative()
model from Saffier
then it will create automatically the following fields:
sender_relation
receiver_relation
For the core use of Saffier, this doesn't do anything and does not impact anything but if you are using a third party package like Esmerald Admin where it uses the Saffier declarative models, then this makes the whole difference to interact with.
Info
In general you don't need to worry about this. This is mainly used by third parties that need to use declarative models from Saffier, like Esmerald Admin.