Henry Kim
Henry Kim

Reputation: 585

flask-sqlalchemy query multiple rows that has different value

I trying to get 2 rows from first, but it should be has different value.

For example,

class Table(db.Model):
    id = db.Column(primary_key)
    category = db.Column(string)
    user_id = db.Column(Integer, Foreign(User))

two_rows = Table.query.filter_by(category='category1').limit(2).all()

With above code, we can get two rows. But it never ensure that each row has different user_id.
How can I ensure (or do query) it?

So I expect the result

Rather than

[
<Table id=1, category='category1', user_id=1>, 
<Table id=2, category='category1', user_id=1>
]

It should be

[
<Table id=1, category='category1', user_id=1>, 
<Table id=3, category='category1', user_id=2>
]

[+] I'm currently using

Upvotes: 0

Views: 1307

Answers (1)

SivolcC
SivolcC

Reputation: 3608

If you want to limit the query to 2 results with distinct user_ids, simply use distinct()

two_rows = Table.query.filter_by(category='category1').distinct(Table.user_id).limit(2).all()

more precisions here, there, and of course the basics here

Upvotes: 1

Related Questions