如何在使用sqlalchemy flask进行分页时跟踪每个项目?

2024-04-20 06:40:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个GETAPI,它将获取所有用户数据并返回它们,现在我计划添加分页

获取API:

model.py
---------
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    username= db.Column(db.String, unique=False, nullable=False)
    city= db.Column(db.String, unique=False, nullable=False)

    def get_user_details(self):
       return temp_dict('username':self.username,'city':self.city)
---------------
api.py
----------------
def get(self):
output_list = []
page_index = request.args.get('index', 1, type=int)
max_item = request.args.get('max', 2, type=int)
list_of_user_obj = User.query.paginate(per_page=max_item, page=page_index)
for each_device_obj in list_of_user_obj.items:
     output_list.append(User.get_user_details(each_device_obj))
 return make_response(jsonify(output_list), status.HTTP_200_OK)

这就是我所做的。在这里,我想跟踪每个项目,如: 如果最终用户要求page=1,那么我应该返回如下内容:

[
 {
   'user_name':'David',
   'city':"CA"
 },
 {
   'user_name':'Sham',
   'city':"NY"
 }
]
-I want to show in UI table like:
list_id|  username | city
1          David       CA
2          Sham        NY
-Now if the user is asking for page=2 in url then my UI table should like:
list_id|  username | city
3          Jack       WA
4          Klane      NY
-Here point is i dont have list_id in my DB , it should generated based on pagination .
So the question here is , Does SQLALCHEMY cover this type of scenario ? How to do this?  


Tags: inselfidfalseobjcityoutputdb
1条回答
网友
1楼 · 发布于 2024-04-20 06:40:40

以下是解决方案:

def get(self):
output_list = []
page_index = request.args.get('index', 1, type=int)
max_item = request.args.get('max', 2, type=int)
init_of_list_id = (page-1)*max_item # Changes Added
list_of_user_obj = User.query.paginate(per_page=max_item, page=page_index)
for each_device_obj in list_of_user_obj.items:
     output_dict =  User.get_user_details(each_device_obj)
     output_dict['list_id'] =  init_of_list_id +1 # Added
     init_of_list_id += 1 # Added
     output_list.append(output_dict)
 return make_response(jsonify(output_list), status.HTTP_200_OK)

相关问题 更多 >