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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.