如何从多个数据库表生成json数据?

时间:2017-04-30 05:35:52

标签: python json peewee

我使用sqlite db和peewee作为ORM。

我的数据模型是:

class User(UserMixin, db.Model):
    nickname = CharField(index=True, unique=True)

class Circle(db.Model):
    name = CharField(unique=True)

class UserInCircle(db.Model):
    user = ForeignKeyField(User, related_name="in_circles")
    circle = ForeignKeyField(Circle, related_name="include_users")
    privilege = IntegerField()

我需要的是获得如下数据格式:

[{"nickname": "urbainy", "privilege": 7, "in_circles": [{"circle_name": "world"}, {"circle_name": "test"}]}, {"nickname": "ywe", "privilege": 1, "in_circles": [{"circle_name": "family"}], {"nickname": "ymo", "privilege": null, "in_circles": []}]

所以这是一个嵌套的json对象。我尝试过棉花糖,但由于多对多的数据结构,我失败了。我不能一直得到in_circles字段。我是程序员的初学者,所以也许这个问题很低级。但我真的没有想法解决它。非常感谢你!

1 个答案:

答案 0 :(得分:0)

现在,我采用这种方式解决问题:

@login_required
def setting():
    users_in_circles = (User.select(User.nickname,
                                    UserInCircle.privilege,
                                    Circle.name.alias("circle_name"))
                            .join(UserInCircle, JOIN.LEFT_OUTER)
                            .join(Circle, JOIN.LEFT_OUTER)
                            .order_by(User.id))
    users_in_circles_data = []
    user_nickname = ""
    user_in_circles = []
    for user_in_circle in users_in_circles.naive():
        if user_in_circle.nickname != user_nickname:
            user_nickname = user_in_circle.nickname
            user_in_circles = [dict(circle_name=str(user_in_circle.circle_name), privilege=str(user_in_circle.privilege))]
            users_in_circles_data.append(dict(nickname=user_in_circle.nickname, in_circles=user_in_circles))
        else:
            user_in_circles.append(dict(circle_name=str(user_in_circle.circle_name), privilege=str(user_in_circle.privilege)))
            users_in_circles_data[-1].update(nickname=user_in_circle.nickname, in_circles=user_in_circles)
    print(users_in_circles_data)
    return render_template("admin_setting.html", circles=Circle.select(), users=User.select(), users_in_circles_data=users_in_circles_data)

不知何故,我想也许还有其他一些巧妙的方法可以实现这一点,比如棉花糖或其他一些工具。如果您知道更好的解决方案,欢迎回复我的帖子。