1.12 2024-01-07 17:59 采纳率: 0%
浏览 2

怎样才能将query.all得到的列表转换成字典

query.all()取到的数据是一个列表,怎么样才能将这个列表中的数据转换成字典形式

 def get(self):
        # 拿到数据库中所有的数据
        data = Article.query.all()

        # 将查询到的数据转换为json格式并返回
        result = [{'title': item.title, 'content': item.content, 'thumbnail': item.thumbnail} for item in data]

        return jsonify(result)

得到的是一个列表

[
  {
    "content": "公称界任员四深根样原这律学。好林权布段八观热石结却又科速。眼器事商求联统总十知区为例体许下。么总文不科律认量社际也进铁。",
    "thumbnail": "http://dummyimage.com/200x100",
    "title": "图价命与法调府"
  },
  {
    "content": "设步铁象中南决门专上由通府调般和。状约长从克酸论史指位花小都车采定。三叫音决看矿了划研除来平际周。入产作制布两合料关技验入天体点教王况。",
    "thumbnail": "http://dummyimage.com/160x600",
    "title": "美权件比何"
  },
  {
    "content": "设步铁象中南决门专上由通府调般和。状约长从克酸论史指位花小都车采定。三叫音决看矿了划研除来平际周。入产作制布两合料关技验入天体点教王况。",
    "thumbnail": "http://dummyimage.com/160x600",
    "title": "美权件比何"
  }
]

我应该怎样修改代码才能转换成字典
这是数据模型

from News import db


class Article(db.Model):
    __tablename__ = 'article'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(100), nullable=False, comment='标题')
    content = db.Column(db.Text, nullable=False, comment='正文')
    thumbnail = db.Column(db.String(255), comment='缩略图')

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2024-01-07 20:13
    关注

    【以下回答由 GPT 生成】

    To convert the list obtained from query.all() into a dictionary format using the given data model, you can modify the code as follows:

    def get(self):
        # Fetch all data from the database
        data = Article.query.all()
    
        # Create an empty dictionary
        result = {}
    
        # Iterate over each item in the retrieved data
        for item in data:
            # Create a unique key using the item's id
            key = item.id
    
            # Create a sub-dictionary using the item's attributes
            value = {
                'title': item.title,
                'content': item.content,
                'thumbnail': item.thumbnail
            }
    
            # Add the sub-dictionary to the main dictionary using the unique key
            result[key] = value
    
        # Return the dictionary as JSON
        return jsonify(result)
    

    This code will convert the list into a dictionary where each item's id is used as the key and the item's attributes (title, content, thumbnail) are used as the values in the sub-dictionary.


    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

问题事件

  • 创建了问题 1月7日