Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Smart querying performing multiple joins #45

Open
AbdealiLoKo opened this issue Aug 14, 2020 · 2 comments
Open

Smart querying performing multiple joins #45

AbdealiLoKo opened this issue Aug 14, 2020 · 2 comments

Comments

@AbdealiLoKo
Copy link

AbdealiLoKo commented Aug 14, 2020

I have the following db structure:

from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship


class Author(BaseModel):
    __tablename__ = 'author'
    id = Column(Integer, primary_key=True)
    first_name = Column(String(255), nullable=False)
    last_name = Column(String(255), nullable=False)


class Book(BaseModel):
    __tablename__ = 'book'
    id = Column(Integer, primary_key=True)
    name = Column(String(255), nullable=False)
    author_id = Column(Integer, ForeignKey('author.id'), nullable=False)

    author = relationship(Author, lazy='selectin')

And I was trying to do something like the following in django:

Book.query.filter(author__first_name='a').filter(author__last_name='b')

And I tried the following in smart_query, and found that it was doing 2 joins - while Django does just 1 join

>>> from sqlalchemy_mixins.smartquery import smart_query

>>> query = Book.query
>>> query = smart_query(query, filters={'author___name': 'a'})
>>> print(query)
SELECT * FROM book
LEFT OUTER JOIN author_ ON author.id = book.author_id
WHERE author.name = 'a'

>>> query = smart_query(query, filters={'author___name': 'b'})
>>> print(query)
SELECT * FROM book
LEFT OUTER JOIN author_1 ON author_1.id = book.author_id
LEFT OUTER JOIN author_2 ON author_2.id = book.author_id
WHERE author_1.first_name = 'a' AND author_2.last_name = 'b'

This seems like a major issue for me - because it doesn't allow me to chain my filters easily.

Am I missing something ? I was planning on adding smart_query to my BaseQuery in sqlalchemy and use that - but this makes it difficult for me to chain my filters

@lovetoburnswhen
Copy link

Any news?

@michaelbukachi
Copy link
Collaborator

@lovetoburnswhen I'm a bit swamped at the moment. Feel free to do a PR and I'll take a look.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants