A right way to perform “IS NOT DISTINCT FROM” in SQLalchemy
I have a table called product and porting this SQL query with psycopg2 to SQLalchemy.
cur.execute("SELECT id FROM product WHERE pid=%s AND product IS NOT DISTINCT FROM %s AND version IS NOT DISTINCT FROM %s AND build IS NOT DISTINCT FROM %s", (parent_id, item.get("product", None), item.get("version", None), item.get("build", None)))
product_id = cur.fetchone()
I found that SQLalchemy has function isnot_distinct_from() which can be used as a direct substitute to "IS NOT DISTINCT FROM...".
I implemented this code to convert the select query into sqlalchemy.session.query()
# Enhancing SQLalchemy standard class with generation of pure text SQL
class Query(_Query):
def to_sql(self):
dialect = self.session.bind.dialect
return str(self.statement.compile(dialect=dialect))
def __init__(self, entities, session):
super().__init__(entities, session)
print(self.to_sql())
def generate_product_table(base):
class product(base):
__tablename__ = "product"
id = Column('id', Integer, primary_key=True)
pid = Column('pid', Integer)
url = Column('url', VARCHAR(4096), nullable=False)
product = Column('product', VARCHAR(4096), nullable=True)
version = Column('version', VARCHAR(4096), nullable=True)
build = Column('build', VARCHAR(4096), nullable=True)
date = Column('date', DateTime(timezone=False), server_default=func.now(), nullable=False)
return product
class SomeClass():
def create_tables(self):
self.Product = generate_product_table(self.basemodel)
self.basemodel.metadata.create_all(bind=self.engine)
def some_method(self, item, parent_id):
self.create_tables()
# Here we have already engine and session initialized
product_id = self.session.query(
self.Product # <--- error is here from Traceback
).filter(
self.Product.pid == parent_id
).filter(and_(
self.Product.product.isnot_distinct_from(item.get("product", None)))
).filter(and_(
self.Product.version.isnot_distinct_from(item.get("version", None)))
).filter(and_(
self.Product.build.isnot_distinct_from(item.get("build", None)))
).options(load_only("id")).one_or_none()
if not product_id:
p.url = item["url"]
At the same time it doesn't work producing this error:
Traceback (most recent call last):
File "example.py", line 20, in some_method
self.Product
File "sqlalchemy/orm/session.py", line 1362, in query
return self._query_cls(entities, self, **kwargs)
TypeError: 'str' object is not callable
python sqlalchemy
add a comment |
I have a table called product and porting this SQL query with psycopg2 to SQLalchemy.
cur.execute("SELECT id FROM product WHERE pid=%s AND product IS NOT DISTINCT FROM %s AND version IS NOT DISTINCT FROM %s AND build IS NOT DISTINCT FROM %s", (parent_id, item.get("product", None), item.get("version", None), item.get("build", None)))
product_id = cur.fetchone()
I found that SQLalchemy has function isnot_distinct_from() which can be used as a direct substitute to "IS NOT DISTINCT FROM...".
I implemented this code to convert the select query into sqlalchemy.session.query()
# Enhancing SQLalchemy standard class with generation of pure text SQL
class Query(_Query):
def to_sql(self):
dialect = self.session.bind.dialect
return str(self.statement.compile(dialect=dialect))
def __init__(self, entities, session):
super().__init__(entities, session)
print(self.to_sql())
def generate_product_table(base):
class product(base):
__tablename__ = "product"
id = Column('id', Integer, primary_key=True)
pid = Column('pid', Integer)
url = Column('url', VARCHAR(4096), nullable=False)
product = Column('product', VARCHAR(4096), nullable=True)
version = Column('version', VARCHAR(4096), nullable=True)
build = Column('build', VARCHAR(4096), nullable=True)
date = Column('date', DateTime(timezone=False), server_default=func.now(), nullable=False)
return product
class SomeClass():
def create_tables(self):
self.Product = generate_product_table(self.basemodel)
self.basemodel.metadata.create_all(bind=self.engine)
def some_method(self, item, parent_id):
self.create_tables()
# Here we have already engine and session initialized
product_id = self.session.query(
self.Product # <--- error is here from Traceback
).filter(
self.Product.pid == parent_id
).filter(and_(
self.Product.product.isnot_distinct_from(item.get("product", None)))
).filter(and_(
self.Product.version.isnot_distinct_from(item.get("version", None)))
).filter(and_(
self.Product.build.isnot_distinct_from(item.get("build", None)))
).options(load_only("id")).one_or_none()
if not product_id:
p.url = item["url"]
At the same time it doesn't work producing this error:
Traceback (most recent call last):
File "example.py", line 20, in some_method
self.Product
File "sqlalchemy/orm/session.py", line 1362, in query
return self._query_cls(entities, self, **kwargs)
TypeError: 'str' object is not callable
python sqlalchemy
2
Please include how you've configured your session to use your custom query class (in other words, provide a Minimal, Complete, and Verifiable example). Your use ofisnot_distinct_from()most probably has nothing to do with the error.
– Ilja Everilä
Nov 21 at 10:06
add a comment |
I have a table called product and porting this SQL query with psycopg2 to SQLalchemy.
cur.execute("SELECT id FROM product WHERE pid=%s AND product IS NOT DISTINCT FROM %s AND version IS NOT DISTINCT FROM %s AND build IS NOT DISTINCT FROM %s", (parent_id, item.get("product", None), item.get("version", None), item.get("build", None)))
product_id = cur.fetchone()
I found that SQLalchemy has function isnot_distinct_from() which can be used as a direct substitute to "IS NOT DISTINCT FROM...".
I implemented this code to convert the select query into sqlalchemy.session.query()
# Enhancing SQLalchemy standard class with generation of pure text SQL
class Query(_Query):
def to_sql(self):
dialect = self.session.bind.dialect
return str(self.statement.compile(dialect=dialect))
def __init__(self, entities, session):
super().__init__(entities, session)
print(self.to_sql())
def generate_product_table(base):
class product(base):
__tablename__ = "product"
id = Column('id', Integer, primary_key=True)
pid = Column('pid', Integer)
url = Column('url', VARCHAR(4096), nullable=False)
product = Column('product', VARCHAR(4096), nullable=True)
version = Column('version', VARCHAR(4096), nullable=True)
build = Column('build', VARCHAR(4096), nullable=True)
date = Column('date', DateTime(timezone=False), server_default=func.now(), nullable=False)
return product
class SomeClass():
def create_tables(self):
self.Product = generate_product_table(self.basemodel)
self.basemodel.metadata.create_all(bind=self.engine)
def some_method(self, item, parent_id):
self.create_tables()
# Here we have already engine and session initialized
product_id = self.session.query(
self.Product # <--- error is here from Traceback
).filter(
self.Product.pid == parent_id
).filter(and_(
self.Product.product.isnot_distinct_from(item.get("product", None)))
).filter(and_(
self.Product.version.isnot_distinct_from(item.get("version", None)))
).filter(and_(
self.Product.build.isnot_distinct_from(item.get("build", None)))
).options(load_only("id")).one_or_none()
if not product_id:
p.url = item["url"]
At the same time it doesn't work producing this error:
Traceback (most recent call last):
File "example.py", line 20, in some_method
self.Product
File "sqlalchemy/orm/session.py", line 1362, in query
return self._query_cls(entities, self, **kwargs)
TypeError: 'str' object is not callable
python sqlalchemy
I have a table called product and porting this SQL query with psycopg2 to SQLalchemy.
cur.execute("SELECT id FROM product WHERE pid=%s AND product IS NOT DISTINCT FROM %s AND version IS NOT DISTINCT FROM %s AND build IS NOT DISTINCT FROM %s", (parent_id, item.get("product", None), item.get("version", None), item.get("build", None)))
product_id = cur.fetchone()
I found that SQLalchemy has function isnot_distinct_from() which can be used as a direct substitute to "IS NOT DISTINCT FROM...".
I implemented this code to convert the select query into sqlalchemy.session.query()
# Enhancing SQLalchemy standard class with generation of pure text SQL
class Query(_Query):
def to_sql(self):
dialect = self.session.bind.dialect
return str(self.statement.compile(dialect=dialect))
def __init__(self, entities, session):
super().__init__(entities, session)
print(self.to_sql())
def generate_product_table(base):
class product(base):
__tablename__ = "product"
id = Column('id', Integer, primary_key=True)
pid = Column('pid', Integer)
url = Column('url', VARCHAR(4096), nullable=False)
product = Column('product', VARCHAR(4096), nullable=True)
version = Column('version', VARCHAR(4096), nullable=True)
build = Column('build', VARCHAR(4096), nullable=True)
date = Column('date', DateTime(timezone=False), server_default=func.now(), nullable=False)
return product
class SomeClass():
def create_tables(self):
self.Product = generate_product_table(self.basemodel)
self.basemodel.metadata.create_all(bind=self.engine)
def some_method(self, item, parent_id):
self.create_tables()
# Here we have already engine and session initialized
product_id = self.session.query(
self.Product # <--- error is here from Traceback
).filter(
self.Product.pid == parent_id
).filter(and_(
self.Product.product.isnot_distinct_from(item.get("product", None)))
).filter(and_(
self.Product.version.isnot_distinct_from(item.get("version", None)))
).filter(and_(
self.Product.build.isnot_distinct_from(item.get("build", None)))
).options(load_only("id")).one_or_none()
if not product_id:
p.url = item["url"]
At the same time it doesn't work producing this error:
Traceback (most recent call last):
File "example.py", line 20, in some_method
self.Product
File "sqlalchemy/orm/session.py", line 1362, in query
return self._query_cls(entities, self, **kwargs)
TypeError: 'str' object is not callable
python sqlalchemy
python sqlalchemy
asked Nov 21 at 9:16
Anton Kochkov
227112
227112
2
Please include how you've configured your session to use your custom query class (in other words, provide a Minimal, Complete, and Verifiable example). Your use ofisnot_distinct_from()most probably has nothing to do with the error.
– Ilja Everilä
Nov 21 at 10:06
add a comment |
2
Please include how you've configured your session to use your custom query class (in other words, provide a Minimal, Complete, and Verifiable example). Your use ofisnot_distinct_from()most probably has nothing to do with the error.
– Ilja Everilä
Nov 21 at 10:06
2
2
Please include how you've configured your session to use your custom query class (in other words, provide a Minimal, Complete, and Verifiable example). Your use of
isnot_distinct_from() most probably has nothing to do with the error.– Ilja Everilä
Nov 21 at 10:06
Please include how you've configured your session to use your custom query class (in other words, provide a Minimal, Complete, and Verifiable example). Your use of
isnot_distinct_from() most probably has nothing to do with the error.– Ilja Everilä
Nov 21 at 10:06
add a comment |
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53408682%2fa-right-way-to-perform-is-not-distinct-from-in-sqlalchemy%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53408682%2fa-right-way-to-perform-is-not-distinct-from-in-sqlalchemy%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
Please include how you've configured your session to use your custom query class (in other words, provide a Minimal, Complete, and Verifiable example). Your use of
isnot_distinct_from()most probably has nothing to do with the error.– Ilja Everilä
Nov 21 at 10:06