Python flask (Multiple-to-multiple-Table query) and pythonflask
In our study of flask, we will inevitably encounter multiple-to-multiple-table queries. Today I also encountered this problem. So I thought for a long time. I did not come up with a solution. I tried several methods, maybe because I gave up the limitation of my thinking. Later, I went online to Baidu, however, there is still a gap between Baidu's results and what I want. Based on my ideas on Baidu, I also explored my data structure, let's take a look at how I can query it here. First, let's take a look at the code snippets of the database I wrote, so that we can better understand it.
Post_class = db. table ('Post _ class', db. column ('Post _ id', db. integer (), db. foreignKey ('posts. id '), db. column ('classifa _ id', db. integer (), db. foreignKey ('fenlei. id') class Post (db. model): # Article table _ tablename __= 'posts' id = db. column (db. integer, primary_key = True, autoincrement = True) title = db. column (db. string (255), unique = True) text = db. column (db. text () publish_date = db. column (db. dateTime, default = datetime. datetime. now () user_id = db. column (db. integer, db. foreignKey ('users. id ') is_recomment = db. column (db. boolean, default = False) comments = db. relationship ('comment', backref = 'posts', lazy = 'dynamic ') tag = db. relationship ('tag', secondary = posts_tags, backref = db. backref ('posts', lazy = 'dynamic ') classname = db. relationship ('classifa ', secondary = post_class, backref = db. backref ('posts') def _ repr _ (self): return "<Model Post' {} '> ". format (self. title) class Classifa (db. model): # category _ tablename __= 'fenlei' id = db. column (db. integer (), primary_key = True) name = db. column (db. string (64) def _ repr _ (self): return self. name
There are three tables, one of which is the list of articles, and the other is the classification table. Let's think, an article may belong to multiple categories at the same time, so a classification may also belong to multiple articles, so we can all understand this logic. So, my third table shows many-to-many relationships, so how can we query it next? In fact, my current requirement is that I want to find all the articles under a category,
Let's take a look at my code.
Data = Classifa. query. filter_by (name = 'database'). first () data_post = data. posts
Here, I will find this category directly from the category, and then query the articles that belong to this category through the third table. In fact, this is very simple. It may be that my mind was short-circuited at the time, I don't know how to think about it. Now it's still that simple, but what I ignored at the time. Come on, learn the way forward.