Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
    Mohammad Ayoub
    Does anyone have any idea why this happens?
    Mohammad Ayoub
    Does tortoise-orm's bulk_update not support "timestamp with time zone" on PostgreSQL?
    Nathan Ward

    Hi - I'm trying to use Tortoise with fastapi / pydantic, porting over some POC code from Sqlalchemy/FastAPI. I have two basic models - Mailbox and Domain. Both reference eachother - i.e. Mailbox belongs to a domain, Domain has many mailboxes. I also have a "*Summary" version of each - i.e. DomainSummary does not have the Mailboxes, and MailboxSummary only has domain_id rather than the relationship.

    I use this so that when a user queries a Mailbox, they get Mailbox+DomainSummary, and not a big recursive thing.

    I think what I want to do, is use different models for the relationship in different situations. This is easy with Pydantic - but it appears that tortoise requires us to use pydantic_model_creator, which doesn't allow me to specify different pydantic models in certain cases...

    This seems like something that would be fairly common, so I must be missing something?

    Diego Gaona

    How to group data by month using a date field?
    Something like this, but by month:

         result = await model.filter(**used_filters, owner_id=user.id) \
                .annotate(value=Sum("value")).group_by("start_date").values("start_date", "value")
            return result

    I'm using SQLite

    hi ,what is the meaning of "-n auto" in pytest, [tool:pytest] addopts = -n auto --cov=tortoise --tb=native -q
    just new here ,and run make test
    pip install pytest-xdist
    pip install pytest-cov
    maybe this two dependency should add to doc
    Rostislav Aleev
    is it possible to generate model from schema (i.e. pydantic model) and initialize it in current Tortoise release?
    Снимок экрана 2021-12-02 в 16.08.49.png
    How to create Pydantic alias like this in Pydantic
    In tortoise model
    Michal Janočko
    Hi guys,
    I'm building an API with FastAPI and Tortoise. I have an integer primary key and I want to have it included in await CategoryResponse.from_tortoise_orm(category). How does one achieve that? The id field is always omitted for me.
    CategoryResponse is the pydantic model for responses CategoryResponse = pydantic_model_creator(Categories).
    Vismay Tiwari
    Hey every one. My team is using FAST API + Tortoise + Gunicorn (Uvicorn worker) + Aws Aurora postgres. Everything works fine on Server side But on DB side , we a very frequent error. "could not recieve data from client: Connection reset by peer". As per my research this issue is not from DB but from server but server side logs show nothing on this. Can anyone help me how to actually fix or debug the issue. I have properly init the tortoise orm and closed it on shutdown but it is unsloved. If anyone want ask anything , Please ask. Thank you. for more detail. tortoise/tortoise-orm#1036
    Diego Gaona
    I don't know if it is it, but I use: await schema.from_queryset_single(model.get().all) or await schema.from_queryset( model.all())
    Brandan Glendenning
    anybody know of any information about queryset evaluation & practices?
    1 reply
    i looked through the docs and didn't find any references
    also, i'm coming from a non-async django orm background...can anybody recommend somewhere to look at implementations of something like conditional filter chaining?
    Good afternoon. Who is aware of the implementation - (tortoise-orm html page)
    Omar Bohsali

    Hi, good morning all! Is anyone here looking for a short 1-2 hour paid consulting engagement today? Some background:

    • I've written a small API in python 3.9 using fastapi, and of course, tortoise ORM.
    • People are starting to use it and I need to write some tests for it.
    • I have simple tests going, but I need to set up my test suite so I can use tortoise orm to create/destroy test fixtures.

    I've seen a couple of github threads about doing this, but would love to screen-share and pair with someone who knows what they're doing better than I do. Thanks!

    Hello everyone! Does there exist a way to use custom column operators, like ~* for postgres pattern matching? https://www.postgresql.org/docs/9.3/functions-matching.html
    In sqlalchemy there was an .op() function which I used

    The filters isnull or not_isnull are not working for me on foreignkey fields
    queryset = queryset.filter(parent_category__not_isnull=False)

    tortoise.exceptions.FieldError: Unknown filter param 'not_isnull'. Allowed base values are ['attributes', 'created_at', 'id', 'is_active', 'last_modified_at', 'name', 'parent_category', 'parent_category_id', 'product_families', 'slug', 'sub_categories']

    Also getting an error with the date filters such as:
    queryset = queryset.filter(created_at__year=2022)
    AttributeError: 'int' object has no attribute 'utcoffset'

    Anyone else experiencing this?

    Pavel Kulikov
    Is it possible to run tortoise ORM functions as sync, without await? I have combination of fastapi and third-party library(xero-pyhton), that use only sync calls, and i need tortoise data in that library.
    Martin Korbel

    Hi folks,
    I have the standard Tortoise class User, which has one special method default_device_group. This method returns a default device group for the user (the return value is getting from a different source).

    class UserPyShow(pydantic_model_creator(User)):    
        user_groups: List[UserGroupPySimple]
        class Config:
            extra = Extra.allow
    @router.get("/me", response_model=UserPyShow)
    async def get_my_profile(user=Security(get_me)):
        res = (await UserPyShow.from_tortoise_orm(user)).dict()
        res['default_device_group'] = await user.default_device_group()
        return res

    This way is not nice and the swagger (/docs) does not show information about default_device_group.
    Does exist some better way how can I extend Pydantic class?

    I have tried to define default_device_group in UserPyShow, but always I get a validation error.

    Does anyone know what Resetting connection with an active transaction <asyncpg.connection.Connection object at 0x000002094F816C00> means? I made an issue 2 months ago and nobody has responded. getting frustrated because this thing is just spamming my console
    Furkan Guvenc

    Hi I am developing FastApi application with tortoise, postgresql and pytest. I can test my application with sqlite, but when I try to test with PostgreSQL it raises an error:

    asyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress

    It first creates a db and tables. Then, tries to execute an insert statement, but fails with this error.

    Rostislav Aleev
    Do you use model or connection and SQL statement? Tortoise has no integration with pytest, just use fixture('session') and close connection after each test function
    Furkan Guvenc

    This is my fixture:

    @pytest.fixture(scope="session", autouse=True)
    def client() -> Generator:
        db_url = f"postgres://{settings.POSTGRES_USER}:{settings.POSTGRES_PASSWORD}@{settings.POSTGRES_HOST}:{settings.POSTGRES_PORT}/test_" + "{}"
        initializer(DB_MODULES["models"], db_url=db_url, app_label="models")
        with TestClient(app) as c:
            yield c

    It creates the db and tables, but raises error when any request is made
    Like this:

    @router.post("", response_model=Store_Pydantic)
    async def create_store(store: StoreIn_Pydantic):
        obj = await StoreModel.create(**store.dict(exclude_unset=True))
        return await Store_Pydantic.from_tortoise_orm(obj)
    Rostislav Aleev
    Don't use initializer and finalizer. Move fixture to module where your test functions are. Use init/yield/close connections
    Furkan Guvenc
    How, can you give me an example?
    I took initializer and finalizer from tortoise-fastapi example
    Rostislav Aleev



    you can use conftest or just use in your module if all tests for ORM are in one module

    Furkan Guvenc
    @rsaleev didn't work
    Joaquim Teixeira Duarte
    Hey guys, I'm getting some difficulty iterating over a QuerySet inside an async for
    can anyone help me?
    Hi, I'm using tortoise-orm 0.16 for a while ...and can't find a way to filter datetime fields by year, month....I try something like this model.filter(datetime__icontains=year, datetime__icontains=month)
    but it's not working...any help please!
    please some help!

    Hello, i want to filter a json field containing a list of int, to find an entry that cointains a value:

    class MyModel(Model):
        foo = fields.JSONField()
    # objects:
    await MyModel.create(foo=[1,2,3])
    await MyModel.create(foo=[123, 456])
    matches = await MyModel.filter(foo__contains=123)

    Matches should find the second object. But it contains both objects...

    I'm using sqlite

    @long2ice do you think you can help me out? sorry for the direct ping
    @chrisdewa can you try changing the query to: matches = await MyModel.filter(foo__contains=[123])
    Markas Klapovščiuk
    Hi, can someone help me with this issue? tortoise/tortoise-orm#1093
    hmm.. looks like issue #1093 is closed
    Jim Stoll
    Sorry for the noob question - I have a dockerized project using Aerich that I'd like to share with others on my team. I have a working config, the database has the aerich and tortoise model tables, etc. When another team member pulls the repo and does a build and up via docker compose, they start with a blank database, of course. (local docker volumes for each person's local development environment) They need a way to initialize the db w/ the aerich table, so they can then do an upgrade from existing migrations scripts in migrations/models (ie, the base database structure for the project.) You can't do an init-db (to create the aerich table), however, w/ an existing migrations/models directory. I don't want them blowing away that directory and generating new migrations scripts, as then their models directory will be out of whack with the base project (ie, they'll now have migrations files based on today's date, vs the migrations files they got in the pull from the repo). How should I go about allowing them to init the db (ie, create the aerich table), then upgrade via the existing migrations in migrations/models?
    Jim Stoll
    (I guess I should have specified 'the Aerich way' - at present, my workaround is to manually create the aerich table in my db init script in docker-entrypoint-initdb.d in my db container - this works, but it feels dirty (and heaven forbid if the aerich table structure should ever change, my script wouldn't do anything to accommodate that. I feel like I must have missed something though, as it probably shouldn't be a dirty manual hack...)
    where_keys = {'created': ('>', date_from), 'created': ('<', date_to)}
    I am getting an error: Dictionary contains duplicate keys 'created'
    How to resolve it without using tortoise query utils Q ?
    Hello, I am a little confused right now. Is there a way to get only the FK (i.e. only the int that is stored in the database) from the ORM and not the queryset?