Viaches
Viaches

Reputation: 401

How get entries between numbers with help SQL-Alchemy

I tried to get as

posts_q = Post_Data.query.filter(Count_Data.number.between(26000, 52000)).all()

returns all (## 1,2,3,4) posts, but

posts_q = Post_Data.query.filter(Count_Data.number.between(26000, 33000)).all()

no entries Why?

models.py

class Post_Data(db.Model):
  __tablename__ = 'post_data'
  # ...
  terms_id = db.Column(db.Integer, db.ForeignKey('count_data.id'))

class Count_Data(db.Model):
  __tablename__ = 'count_data'
  # ...
  number = db.Column(db.Integer)
  posts = db.relationship('Post_Data', backref='counts', lazy='dynamic')

sql

#1 Count_Data.number = 8000
#2 Count_Data.number = 23000
#3 Count_Data.number = 46000
#4 Count_Data.number = 78000

Upvotes: 4

Views: 2466

Answers (1)

Viaches
Viaches

Reputation: 401

I found a solution, it was necessary to use .join():

Post_Data.query.join(Count_Data).filter(Count_Data.number.between(26000, 52000)).all()

returns #3 entry

for consistent comparisons don't need to call .join()

q = Post_Data.query
q = q.join(Count_Data).filter(Count_Data.number >= 26000)
q = q.filter(Count_Data.number <= 52000)
q = q.all()

Upvotes: 3

Related Questions