[Python] Writing a tuple search with Django ORM

Discussão em 'Python' iniciado por Stack, Fevereiro 15, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to write a search based on tuples with the Django ORM syntax.

    The final sql statement should look something like:

    SELECT * FROM mytable WHERE (field_a,field_b) IN ((1,2),(3,4));


    I know I can achieve this in django using the extra keyword:

    MyModel.objects.extra(
    where=["(field_a, field_b) IN %s"],
    params=[((1,2),(3,4))]
    )


    but the "extra" keyword will be deprecated at some point in django so I'd like a pure ORM/django solution.

    Searching the web, I found https://code.djangoproject.com/ticket/33015 and the comment from Simon Charette, something like the snippet below could be OK, but I can't get it to work.

    from django.db.models import Func, lookups

    class ExpressionTuple(Func):
    template = '(%(expressions)s)'
    arg_joiner = ","


    MyModel.objects.filter(lookups.In(
    ExpressionTuple('field_a', 'field_b'),
    ((1,2),(3,4)),
    ))


    I'm using Django 3.2 but I don't expect Django 4.x to do a big difference here. My db backend is posgresql in case it matters.

    Continue reading...

Compartilhe esta Página