Search code examples
pythondjangoasynchronousorm

Django ORM Q and Async


I'm using django with Telegram Bot

If i need to make ORM Query, i can do it like that

    all_offers = await sync_to_async(Offers.objects.filter, thread_sensitive=True)(
        status      = True,
    )

but not i need to make more difficult query with Q function like that

    all_offers = await sync_to_async(Offers.objects.filter, thread_sensitive=True)(
        status      = True,
        Q(some_field="1")|Q(another_field=2),
    )

SyntaxError: positional argument follows keyword argument

How it can be solved?


Solution

  • as the error says, you can not place positional parameters after keyword ones, so you should put the Q object first:

    all_offers = await sync_to_async(Offers.objects.filter, thread_sensitive=True)(
        Q(some_field='1') | Q(another_field=2),
        status=True,
    )

    Using an asynchronous filter however does not make much sense: .filter() is lazy: that means that you only construct a QuerySet asynchronously, not fetch the records themselves in an asynchronous manner. The reason there is no .afilter(…), .aannotate(…), etc. is because these do not generate a query, only produce a new QuerySet that might (or will not) eventually make a database query.

    You can make use of an async for when you enumerate over the queryset. For more information, see the Asynchronous support section of the documentation.