Compile a Python script to convert a sqlAlchemy object to a dict tutorial-Python tutorial

Source: Internet
Author: User
This article describes how to write a Python script to convert a sqlAlchemy object to dict. It mainly builds a conversion method based on the Python model class, if you want to write a web application using sqlAlchemy, you may often use json for communication. dict is the closest object to json, sometimes it is more convenient to operate dict than to operate ORM objects. after all, you don't have to worry about the database session status.

Assume that there is a post table in the database, one of the methods is

p = session.query(Post).first()p.__dict__

However, since p is an object of sqlAlchemy, we do not need to pay attention to other attributes in p. _ dict _, such as _ sa_instance.

Then we can add a method to the base class of the model, assuming that the original method in models. py is as follows:

Base = sqlalchemy.ext.declarative.declarative_base()class Post(Base):  __tablename__ = 'post'  id = Column(Integer, primary_key=True)  title = Column(String)

Then we can add a to_dict () method to the Base class.

def to_dict(self):  return {c.name: getattr(self, c.name, None) for c in self.__table__.columns}Base.to_dict = to_dict

In this way, you can

p = session.query(Post).first()p.to_dict()

Of course, if the model is not bound to the table, there is no _ table _ information in the model, which may cause problems, but I think this is the most convenient at present.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.