0

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

  • postgresql
  • flask-sqlalchemy
davidism
  • 121,510
  • 29
  • 395
  • 339
Henry Kim
  • 575
  • 4
  • 19

1 Answers1

1

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

SivolcC
  • 3,258
  • 2
  • 14
  • 32