How to compile a Python script to convert a sqlAlchemy object to dict

Source: Internet
Author: User

How to compile a Python script to convert a sqlAlchemy object to dict

This article mainly introduces how to compile a Python script to convert the sqlAlchemy object to dict. It mainly constructs a conversion method based on the Python model class. For more information, see

When using sqlAlchemy to write a web application, it often uses json for communication. The object closest to json is dict. 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

?

1

2

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:

?

1

2

3

4

5

6

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.

?

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

In this way, you can

?

1

2

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.