Skip to content

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 edgy
from edgy import Database, Registry

database = Database("sqlite:///db.sqlite")
models = Registry(database=database)


# Declare the Edgy model


class User(edgy.Model):
    is_active: bool = edgy.BooleanField(default=True)
    first_name: str = edgy.CharField(max_length=50)
    last_name: str = edgy.CharField(max_length=50)
    email: str = edgy.EmailField(max_lengh=100)
    password: str = edgy.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, Edgy will generate a SQLAlchemy Relationship for you automatically and append relation at the end of the declared field.

Let us see an example.

import edgy
from edgy import Database, Registry

database = Database("sqlite:///db.sqlite")
models = Registry(database=database)


class User(edgy.Model):
    is_active: bool = edgy.BooleanField(default=True)
    first_name: str = edgy.CharField(max_length=50)
    last_name: str = edgy.CharField(max_length=50)
    email: str = edgy.EmailField(max_lengh=100)
    password: str = edgy.CharField(max_length=1000)

    class Meta:
        registry = models


class Thread(edgy.Model):
    sender: User = edgy.ForeignKey(
        User,
        on_delete=edgy.CASCADE,
        related_name="sender",
    )
    receiver: User = edgy.ForeignKey(
        User,
        on_delete=edgy.CASCADE,
        related_name="receiver",
    )
    message: str = edgy.TextField()

    class Meta:
        registry = models

As you can see, the model Thread has two foreign keys, sender and receiver. In a normal Edgy ORM operation, this remains as is but if you generate the declarative() model from Edgy then it will create automatically the following fields:

  • sender_relation
  • receiver_relation

For the core use of Edgy, 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 Edgy 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 Edgy, like Esmerald Admin.