I have the following models and table:
chat_members = db.Table('chat_members',
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('chat_id', db.Integer, db.ForeignKey('chat.id'))
)
class chat(db.Model):
id = db.Column(db.Integer, primary_key=True)
start_date = db.Column(db.DateTime)
chat_memb = db.relationship('user', secondary=chat_members, backref=db.backref('members', lazy='dynamic'))
chat_line = db.relationship('line', backref='chat_line', lazy='dynamic')
def __repr__(self):
return '<Chat %r>' % (self.id)
class user(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_email = db.Column(db.String, unique=True)
user_password = db.Column(db.String)
lines = db.relationship('line', backref='line_author', lazy='dynamic')
def __repr__(self):
return '<User %r>' % (self.user_email)
class line(db.Model):
id = db.Column(db.Integer, primary_key=True)
published_date = db.Column(db.DateTime)
chat_id = db.Column(db.Integer, db.ForeignKey('chat.id'))
sent_by = db.Column(db.Integer, db.ForeignKey('user.id'))
line_text = db.Column(db.String)
def __repr__(self):
return '<Line %r>' % (self.id)
I have successfully added data to all of these models but am having trouble querying the table. The ultimate goal of the query is to look up all of the chats associated with a particular user. Here is what I have done:
first_user = user.query.get(1)
chat.query.filter(chat_members.any(chat_memb=first_user)).all()
To which I got
sqlalchemy.exc.InvalidRequestError: Can’t compare a collection to an
object or collection; use contains() to test for membership.
This question (http://stackoverflow.com/questions/12593421/sqlalchemy-and-flask-how-to-query-many-to-many-relationship) seemed very similar, but when I duplicated it for my model, I got AttributeError: type object 'chat' has no attribute 'members' after doing
chat.query.filter(chat.members.any(user_email='ACCEPTABLE_EMAIL')).all()
The traceback came as a surprise seeing as members is the backref within the chat model, but I feel like this query comes close.
The other relevant questions I could find did not seem to offer advice on the same search, and I could not find such queries in the official or a 3rd party many-to-many documentation.
You need to use joins in your query. First change your
chat.chat_membrelationship to:Then use this query:
I also recommend to follow Python style guidelines and use capitalized names for classes, e.g.
Chatinstead ofchat. It’s easy to confuse a class and an instance in your code now.