Post Model

def post_struct(UserStruct):
    """
    Post Model

    """

    db = UserStruct.User.db

    class SlugNameMixin(object):
        name = db.Column(db.String(250))
        slug = db.Column(db.String(250), index=True, unique=True)

        @classmethod
        def get_by_slug(cls, slug):
            """
            Return a post by slug
            """
            return cls.all().filter(cls.slug == slug).first()

        @classmethod
        def new(cls, name, slug=None):
            slug = utils.slug(name if not slug else slug)
            return cls.create(name=name, slug=slug)

        def rename(self, name, slug=None):
            slug = utils.slug(name if not slug else slug)
            return self.update(name=name, slug=slug)

    class PostType(SlugNameMixin, db.Model):
        @property
        def total_posts(self):
            return Post.all().filter(Post.type_id == self.id).count()

    class PostCategory(SlugNameMixin, db.Model):
        @property
        def total_posts(self):
            return PostPostCategory.all()\
                .filter(PostPostCategory.category_id == self.id)\
                .count()

    class PostPostCategory(db.Model):
        post_id = db.Column(db.Integer, db.ForeignKey("post.id"))
        category_id = db.Column(db.Integer, db.ForeignKey(PostCategory.id))

        @classmethod
        def add(cls, post_id, category_id):
            c = cls.all().filter(cls.post_id == post_id)\
                .filter(cls.category_id == category_id)\
                .first()
            if not c:
                cls.create(post_id=post_id, category_id=category_id)

        @classmethod
        def remove(cls, post_id, category_id):
            c = cls.all().filter(cls.post_id == post_id)\
                .filter(cls.category_id == category_id)\
                .first()
            if c:
                c.delete(hard_delete=True)

    class Post(db.Model):

        user_id = db.Column(db.Integer, db.ForeignKey(UserStruct.User.id))
        type_id = db.Column(db.Integer, db.ForeignKey(PostType.id))
        parent_id = db.Column(db.Integer)
        revision_id = db.Column(db.Integer)
        title = db.Column(db.String(250))
        slug = db.Column(db.String(250), index=True)
        content = db.Column(db.Text)
        excerpt = db.Column(db.Text)
        is_public = db.Column(db.Boolean, index=True, default=False)
        is_sticky = db.Column(db.Boolean, index=True, default=False)
        is_published = db.Column(db.Boolean, index=True, default=True)
        is_draft = db.Column(db.Boolean, index=True, default=False)
        is_revision = db.Column(db.Boolean, default=False)
        published_date = db.Column(db.DateTime)
        author = db.relationship(UserStruct.User, backref="posts")
        type = db.relationship(PostType, backref="posts")
        categories = db.relationship(PostCategory,
                                     secondary=PostPostCategory.__table__.name)


        @classmethod
        def new(cls, title, **kwargs):
            """
            Insert a new post
            """
            published_date = None
            is_revision = False
            is_published = False
            is_draft = False
            is_public = kwargs["is_public"] if "is_public" in kwargs else True
            parent_id = int(kwargs["parent_id"]) if "parent_id" in kwargs else None
            if "is_revision" in kwargs and kwargs["is_revision"] is True:
                if not parent_id:
                    raise ModelError("'parent_id' is missing for revision")
                is_revision =True
                is_public = False
            elif "is_draft" in kwargs and kwargs["is_draft"] is True:
                is_draft = True
                is_public = False
            elif "is_published" in kwargs and kwargs["is_published"] is True:
                is_published = True
                published_date = datetime.datetime.now()

            slug = ""
            if is_published or is_draft:
                slug = cls.create_slug(title if "slug" not in kwargs else kwargs["slug"])

            data = {
                "title": title,
                "slug": slug,
                "content": kwargs["content"] if "content" in kwargs else "",
                "excerpt": kwargs["excerpt"] if "excerpt" in kwargs else "",
                "is_published": is_published,
                "published_date": published_date,
                "is_draft": is_draft,
                "is_revision": is_revision,
                "is_public": is_public,
                "parent_id": parent_id,
                "type_id": kwargs["type_id"] if "type_id" in kwargs else None
            }
            return cls.create(**data)

        @classmethod
        def get_published(cls, id=None, slug=None):
            """
            Get a published post by id or slug
            :param id: The id of the post
            :param slug: str - The slug to look for
            """
            post = None
            if id:
                post = cls.get(id)
            elif slug:
                post = cls.get_by_slug(slug)
            return post if post and post.is_published else None

        @classmethod
        def get_published_by_category_slug(cls, slug):
            """
            Query by category slug
            :return SQLA :
            """
            return cls.all()\
                .join(PostPostCategory)\
                .join(PostCategory)\
                .filter(PostCategory.slug == slug)\
                .filter(cls.is_published == True)

        @classmethod
        def get_published_by_type_slug(cls, slug):
            """
            Query by type slug
            :return SQLA :
            """
            return cls.all()\
                .join(PostType)\
                .filter(PostType.slug == slug)\
                .filter(cls.is_published == True)

        @classmethod
        def create_slug(cls, title):
            slug_counter = 0
            _slug = utils.slug(title).lower()
            while True:
                slug = _slug
                if slug_counter > 0:
                    slug += str(slug_counter)
                    slug_counter += 1
                if not cls.get_by_slug(slug):
                    break
            return slug

        @classmethod
        def get_by_slug(cls, slug):
            """
            Return a post by slug
            """
            return cls.all().filter(cls.slug == slug).first()

        def publish(self, published_date=None):
            if self.is_draft:
                data = {
                    "is_draft": False,
                    "is_published": True,
                    "published_date": published_date or datetime.datetime.now()
                }
                self.update(**data)

        def set_type(self, type_id):
            self.update(type_id=type_id)

        def set_slug(self, title):
            slug = utils.slug(title)
            if title and slug != self.slug:
                slug = self.create_slug(slug)
                self.update(slug=slug)

        def replace_categories(self, categories_list):
            cats = PostPostCategory.all()\
                    .filter(PostPostCategory.post_id == self.id)
            cats_list = [c.category_id for c in cats]

            del_cats = list(set(cats_list) - set(categories_list))
            new_cats = list(set(categories_list) - set(cats_list))

            for dc in del_cats:
                PostPostCategory.remove(post_id=self.id, category_id=dc)

            for nc in new_cats:
                PostPostCategory.add(post_id=self.id, category_id=nc)

        @property
        def status(self):
            if self.is_published:
                return "Published"
            elif self.is_draft:
                return "Draft"
            elif self.is_revision:
                return "Revision"

        def delete_revisions(self):
            """
            Delete all revisions
            """
            try:
                Post.all()\
                    .filter(Post.post_id == self.id)\
                    .filter(Post.is_revision == True)\
                    .delete()
                Post.db.commit()
            except Exception as ex:
                Post.db.rollback()

        @property
        def total_revisions(self):
            return Post.all()\
                .filter(Post.post_id == self.id)\
                .filter(Post.is_revision == True)\
                .count()


    return utils.to_struct(Post=Post,
                           Category=PostCategory,
                           Type=PostType,
                           PostCategory=PostPostCategory
                           )