Nicolas
Nicolas

Reputation: 9

Tortoise-ORM. Displaying External Entities in PyDantic Models

Faced the problem of displaying external entities in PyDantic models.

I have an entity structure in the database:

class User(models.Model):
    id = fields.BigIntField(pk=True)
    username = fields.CharField(max_length=1024, null=True)

class Message(models.Model):
    id = fields.BigIntField(pk=True)
    date = fields.DatetimeField()
    user: fields.ForeignKeyRelation["User"] = fields.ForeignKeyField("models.User", on_delete=fields.CASCADE)
    text = fields.TextField()

I created models through pydantic_model_creator:

UserRp = pydantic_model_creator(User, name="UserRp")
MessageRp = pydantic_model_creator(Message, name="MessageRp")

I'm trying to call a request through the construction:

await MessageRp.from_queryset(Message.filter(user=user_id).order_by("-date"))

Returns all fields except user. Even if you supplement the string with the prefetch_related("user") method.

Tell me what could be the problem. Adding include to pydantic_model_creator failed

Upvotes: 0

Views: 458

Answers (1)

Nikolay Pavlin
Nikolay Pavlin

Reputation: 365

You should call tortoise intialisation before creating pydantic models:

https://tortoise.github.io/examples/pydantic.html#relations-early-init

Upvotes: 0

Related Questions