Reputation: 53
I'm new to sqlalchemy and flask for that matter but I'm using them for a personal project and i need some help.
I have a column called form_id:
class Entries(db.Model):
form_id = db.Column(db.String(12), index=True)
text = db.Column(db.String(1000), nullable=True, unique=False)
and I'm generating that form id randomly every time the page is refreshed:
form_id = generate_formid(12)
which gives me a 12 character long alphanumeric string.
What i want to do is grab all entries for current_user but separate them by form_id into lists without knowing what the form_id is.
So for example (not real code):
for form_id in query:
get all rows and add them to a list
from:
Entries.query.filter_by(owner_id=current_user.username)
So i need to filter_by owner_id and somehow pull out data for every different form_id into its own list.
What would be the best way of doing this? Any help would be greatly appreciated.
Upvotes: 1
Views: 40
Reputation: 55759
You could use the itertools.groupby function to do this.
import itertools
# Order the query by form_id, because groupby expects a sorted iterable.
ents = Entries.query.filter_by(owner_id=current_user.username).order_by(Entries.form_id)
# Tell groupby that we want to group by form_id, using the key parameter
gb = itertools.groupby(ents, key=lambda ent: ent.form_id)
# Create the list of lists
grouped = [list(group) for _, group in gb]
Upvotes: 2