fastapipydantictortoise-orm

Tortoise ORM. Add additional field to PydanticListModel class generated by pydantic_queryset_creator function


Can you tell me how, when using tortoise.contrib.pydantic.pydantic_queryset_creator, to add an additional field that is generated when querying the database?

Here is the query:

categories = await EquipmentCategory \
    .filter(equipment__organization__inn=organization_inn) \
    .annotate(equipment_count=functions.Count('equipment')) \
    .order_by('-equipment_count') \
    .limit(3) \
    .all()

The pydantic_queryset_creator(EquipmentCategory) class does not contain the equipment_count field, and it is needed during serialization.

I tried to inherit and redefine the field:

class EquipmentCategoryListPydantic(pydantic_queryset_creator(EquipmentCategory)):
    equipment_count: int

But it leads to the exception:

ValueError: __root__ cannot be mixed with other fields

I really don't want to rewrite everything from scratch (using pydantic.BaseModel) and repeat the whole code twice!

I hope for your help!


Solution

  • Solved! (But is it a good solution?).

    I inherited the abstract ORM class EquipmentCategoryWithEquipmentCount from the original ORM class EquipmentCategory and added the equipment_count field to it. Later on in pydantic_queryset_creator I just used this class:

    class EquipmentCategory(models.Model):
        name = fields.CharField(max_length=255)
        created_at = fields.DatetimeField(auto_now_add=True)
    
        class PydanticMeta:
            exclude = ["created_at", "equipment"]
    
    
    class EquipmentCategoryWithEquipmentCount(EquipmentCategory):
        equipment_count = fields.IntField()
    
        class Meta:
            abstract = True
    
    EquipmentCategoryListSchema = pydantic_queryset_creator(EquipmentCategoryWithEquipmentCount)