I have a bunch of users and want to get a list of all the products they have bought. I currently do this with
list_of_products = [user.products.all() for user in all_users]
Where the User table and the Product table are connected by a many-to-many relationship. I noticed that this does not scale very well. If the number of users increases, it can take quite a while. I am trying to understand whether this is due to a overhead when performing a call or whether this is just the scaling because more products are needed?
Basically, what is the fastest way to retrieve all products for a list of users.
Just in case, here are the tables
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
...
products = db.relationship('product',
secondary=sales,
lazy='dynamic')
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
...
sales = db.Table(
'sales',
db.Column('product_id', db.Integer, db.ForeignKey('product.id')),
db.Column('user_id', db.Integer, db.ForeignKey('user.id'))
)