2013-10-10 1 views
0

flask-sqlalchemy를 사용하여이 문을 작성했으며 원래 형식으로 유지하도록 선택했습니다. Post.querysession.query(Post)Sqlalchemy 하위 조건에서 항상 필터 조건이 True를 반환합니다

현재 초안 상태이며 현재 사용자가 작성하거나 수정하지 않은 데이터베이스의 모든 게시물을 필터링하는 하위 쿼리를 만들려고했습니다.

Where true AND ("Post".modified_by_id = :modified_by_id_1 OR 
"Post".created_by_id = :created_by_id_1) 

예상 결과는 : 내가 궁금하네요

Where "Post".post_status != "Draft" AND (
"Post".modified_by_id = :modified_by_id_1 OR 
"Post".created_by_id = :created_by_id_1) 

, 왜 이런 일이 내가 만든이 쿼리,

Post.query\ 
    .filter(sqlalchemy.and_(
     Post.post_status != Consts.PostStatuses["Draft"], 
      sqlalchemy.or_(
       Post.modified_by_id == current_user.get_id(), 
       Post.created_by_id == current_user.get_id())) 

을했다? SQLAlchemy에서 오류 수준을 높이려면 어떻게해야합니까? 내 프로젝트가 조용히 실패하고 내 추측을 확인하고 싶습니다.

업데이트 :

내가 잘못 상수 사전을 사용했다. 하나의 사전은 int를 포함하고 다른 하나는 문자열을 포함합니다 (하나는 데이터베이스 쿼리 용이고 하나는 문자열 용입니다).

_post_status = db.Column(
     db.SmallInteger, 
     default=Consts.post_status["Draft"]) 

post_status에는 정수가 들어 있습니다. Consts.PostStatuses에는 문자열이 들어 있습니다. 뒷모습에서, 정말 나쁜 생각. 두 개의 사전 대신 튜플을 반환하는 하나의 사전을 만들 예정입니다.

@property 
def post_status(self): 
    return Consts.post_status.get(getattr(self, "_post_status", None)) 
+0

Post.post_status 및 Consts.PostStatuses [ "Draft"]는 어떤 유형입니까? Post는 모델입니까? SqlAlchemy는 형식 및 파이썬 매직 메서드를 기반으로 쿼리를 작성합니다. 나는 post_status가 boolean이고 draft가 빈 문자열이라면 확실히 말할 수 있습니다. sqlalchemy는 항상 true SQL 문을 생성합니다. 확실히 다른 경우가 있습니다. –

+0

post_status는 작은 int이고 PostStatuses는 int입니다 (이 경우 1). – AlexLordThorsen

+0

당신은 더 정확한 수 있습니까? 쿼리를 실행하기 직전에'print type (Post.post_status), type (Const.PostStatuses [ "Draft"])'형식을 추가하십시오. ' int' – SingleNegationElimination

답변

2

문제는 post_status 속성이이 python descriptor 인 등의 ORM 수준 쿼리 사용에 대한 허용되지 않는 것입니다 기본 반환 자체 클래스 수준에서 어떤 :

from sqlalchemy import * 
from sqlalchemy.orm import * 
from sqlalchemy.ext.declarative import declarative_base 

Base = declarative_base() 

class A(Base): 
    __tablename__ = 'a' 

    id = Column(Integer, primary_key=True) 

    _post_status = Column(String) 

    @property 
    def post_status(self): 
     return self._post_status 


print (A.post_status) 
print (A.post_status != 5678) 

출력 :

$ python test.py 
<property object at 0x10165bd08> 
True 

당신이 찾고있는 사용의 유형은 "등록에 SQLAlchemy의 포함 확장하는 hybrid attribute, 그처럼 보인다 핵심 SQL 표현식과 호환 클래스 수준의 동작을 생산 울라 "파이썬 설명 :

from sqlalchemy.ext.hybrid import hybrid_property 

class A(Base): 
    __tablename__ = 'a' 

    id = Column(Integer, primary_key=True) 

    _post_status = Column(String) 

    @hybrid_property 
    def post_status(self): 
     return self._post_status 

print (A.post_status) 
print (A.post_status != 5678) 

출력 :

$ python test.py 
A._post_status 
a._post_status != :_post_status_1 

하는 것은 신중하게 모두에서 작동 기술자, how to establish the correct SQL expression behavior를 포함하는 하이브리드 문서를 읽으십시오 인스턴스 및 클래스 수준은 다소 고급 파이썬 기술입니다.

+0

필자는'post_status' 속성 대신'_post_status'를 테스트했습니다. 더 나은 솔루션이라고 생각합니다. – AlexLordThorsen