Many to many relation SQLAlchemy (does relation exsist attribute)
I'm re-asking this question but with a different framework this time. I have two Models: User and Book with a M2M-relation. I want Bo开发者_Python百科ok to have an attribute "read" that is True when the relation exists. Is this possible in SQLAlchemy?
Take a look at SQL Expressions as Mapped Attributes. Something like this should do the job for you:
Book.read = column_property(
select(
[func.count(user_to_book_table.c.user_id)],
user_to_book_table.c.book_id == book_table.c.id
).label('read')
)
Even though it is not Boolean, you can still use it in the IF statements correctly:
if mybook.read:
print 'very popular book indeed'
Alternatively you can just add a computed (read-only) property on the Book object, but this will load all the Users into your session:
@property
def read(self):
return len(self.books)!=0
精彩评论