Making address: https://github.com/honmaple/maple-json

SQLAlchemy Object serialized to JSON

Inspired by the Django REST Framework

More than one instance

posts = Post.query.all()
serializer = Seralizer(posts,many=True)
data = serializer.data

A single instance

post = Post.query.first()
serializer = Seralizer(post,many=False)
data = serializer.data

Rule out field

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

Including fields only

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

Relational query depth

serializer = Seralizer(post,depth=3)
  • depth

    The default value is 2

Add some custom functions

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

Post

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

A function that can pass arguments

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

Use SQLAlchemy just like Django ORM

Why do many people think Django ORM is better than SQLAlchemy

Basic query (implemented)

  • 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()

Relational 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')

Remove some of the duplicated work of SQLAlchemy

In the case of Flask-SQLAlchemy, you can remove some of the duplication by inheriting mixins in models.py

ModelMixin

Auto-increment ID – ID

POST = POST (····) POST. SAVE () # POST. DELETE () # POST

The batch operation

  • bulk_insert

  • bulk_update

  • bulk_save

ModelTimeMixin

Add two fields

  • created_at

    Data creation time
  • updated_at

    Data update time

ModelUserMixin

The User table is associated with a many-to-one relationship with User (i.e., one User has multiple posts).

class Post(ModelUserMixin, Model):

    user_related_name = 'posts'
    titile = ...