Write a Python script to convert a SQLAlchemy object into a dict tutorial

Source: Internet
Author: User
Tags json python script

This article mainly introduced the writing Python script to convert the SQLAlchemy object to the Dict tutorial, mainly based on the Python model class constructs a transformation method, needs the friend to be possible to refer to under

When using SQLAlchemy to write Web applications, often use JSON to communicate, with JSON the closest object is dict, sometimes operation Dict will be more convenient than the operation of ORM objects, after all, do not have to manage the state of database session.

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

?

1 2 p = session.query (Post). A () p.__dict__

But since p is a SQLAlchemy object, there are some other attributes in p.__dict__ such as _sa_instance that we don't need to focus on.

So we can add a method to the model's base class, assuming that it's the same in models.py.

?

1 2 3 4 5 6 Base = Sqlalchemy.ext.declarative.declarative_base () class Post (base): __tablename__ = ' Post ' id = Column (Integer, Prima Ry_key=true) title = Column (String)

So we can add a to_dict () method to the base class

?

1 2 3 4 def to_dict (self): return {c.name:getattr (self, c.name, None) for C in self.__table__.columns} base.to_dict = To_dict

So that we can

?

1 2 p = session.query (Post). A () p.to_dict ()

Of course, if model does not and table binding words model is no __table__ information, may also have problems, but I think this is the most convenient

Related Article

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.