Skip to content
sqlalchemy serializer to json
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.gitignore
LICENSE
README.org

README.org

maple-json

https://img.shields.io/badge/license-BSD-blue.svg https://img.shields.io/badge/python-3.5-green.svg

Serializer sqlachemy object to json

usage

it’s simple to use(take flask-sqlalchemy as an example)

multi instances

posts = Post.query.all()
serializer = Serializer(posts)
data = serializer.data

single instance

post = Post.query.first()
serializer = Serializer(post)
data = serializer.data

exclude some columns

serializer = Serializer(post,exclude=['title'])

only include some column

serializer = Serializer(post,include=['title'])

relation depth

serializer = Serializer(post,depth=3)
  • depth default:2

add some custom function

serializer = Serializer(post,extra=['get_post_count'])

Post

class Post(Model):
    ......
    def get_post_count(self):
        return 11

Other

class PostSerializer(Serializer):
    count = Field(source = 'get_post_count',args={'name':'hello'},default=20)
    class Meta:
        include = []
        depth = 2
        include = []
        exclude = []
        extra = ['count']

Just use sqlalchemy like django orm

base query(have finished)

  • gt
  • lt
  • lte
  • gte
  • contains
  • in
  • exact
  • iexact
  • startswith
  • istartswith
  • iendswith
  • endswith
  • isnull
  • range
  • year
  • month
  • day

Example:

Post.query.filter_by(title__contains = 'sql').all()
Post.query.exclude_by(title__contains = 'sql').all()

relationship query

Post.query.filter_by(tags__name__contains = 'sql').all()

other

Post.query.filter_by(tags__name__contains = 'sql').or(Post.id == 1,Post.id == 2).all()
Post.query.filter_by(tags__name__contains = 'sql').and(Post.id == 1,Post.id == 2).all()
Post.query.filter_by(tags__name__contains = 'sql').exists()
Post.query.load_only('title')

Use sqlalchemy better

take flask-sqlalchemy as an example,you can remove part of the repetitive work by use Mixin of ‘models.py’

ModelMixin

Increment ID – id

post = Post(·····)
post.save() 
post.delete()

bulk operation

  • bulk_insert
  • bulk_update
  • bulk_save

ModelTimeMixin

  • created_at Data create time
  • updated_at Data update time

ModelUserMixin

relate to *User*(many to one)

class Post(ModelUserMixin, Model):

    user_related_name = 'posts'
    titile = ...
You can’t perform that action at this time.