How to create a one to many relationship using Tortoise ORM?

633 Views Asked by At

I am creating an app in which I have a User entity and an Item entity that are related one to many. I am using TORTOISE ORM, in a file with the path: app/models/user.py I have the following code:

from tortoise import fields

from app.models.base_class import Base


class User(Base):
    name = fields.CharField(max_length = 50, nullable = False)
    last_name = fields.CharField(max_length = 50, nullable = False)
    email = fields.CharField(max_length = 128, unique = True, nullable = False)
    password = fields.CharField(max_length = 128, nullable = False)
    create_date = fields.DatetimeField(auto_now = True)

    class Meta:
        table = 'user_db'

Hello, I am creating an app in which I have a User entity and an Item entity that are related one to many. I am using TORTOISE ORM, in a file with the path: app/models/user.py I have the following code:

And in the path: app/models/item.py I have the following code:

from tortoise.models import Model
from tortoise import fields

from app.models.base_class import Base

class Item(Base):
    title = fields.CharField(max_length = 50, nullable = False)
    description = fields.TextField(nullable = False)
    weight = fields.DecimalField(max_digits=3)
    cost = fields.DecimalField(max_digits=3)
    url_image = fields.CharField(max_length = 255)
    user_id = fields.ForeignKeyField(
        'app.models.user.User',
        'id',
        on_delete = fields.CASCADE
    )

My question is if I am correctly implementing the foreign key in the user_id field, is it correct to write the path 'app.models.user.User' for the model name parameter? Do I have to import User in item.py to be able to do this? Or, on the other hand, should I write in this parameter is 'user_db', which will be the name of the User model table? I'm tangled up with this.

1

There are 1 best solutions below

0
On

Creating such a relation is possible with ForeignKeyField. The field should be defined on the "many" side, and related_name can be used to define to the name of the "auto-generated field" on the "one" side of the relation (so it can query the many objects connected to it). Take a look at the Book model in the tests (https://github.com/tortoise/tortoise-orm/blob/develop/tests/testmodels.py#L39) and how this model is used in the tests as well.