Flask Postgresql数组无法永久更新 [英] Flask Postgresql array not permanently updating

查看:61
本文介绍了Flask Postgresql数组无法永久更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有Flask和PostgreSQL数据库以及SQLAlchemy的项目.

I'm working on a project using Flask and a PostgreSQL database, with SQLAlchemy.

我有Group个对象,这些对象具有作为组成员的User个ID的列表.由于某些原因,当我尝试将ID添加到组中时,该ID将无法正确保存.

I have Group objects which have a list of User IDs who are members of the group. For some reason, when I try to add an ID to a group, it will not save properly.

如果我尝试members.append(user_id),它似乎根本不起作用.但是,如果尝试members += [user_id],则ID将显示在列出所有组的视图中,但是如果我重新启动服务器,则不存在增加的值.但是,初始值是.

If I try members.append(user_id), it doesn't seem to work at all. However, if I try members += [user_id], the id will show up in the view listing all the groups, but if I restart the server, the added value(s) is (are) not there. The initial values, however, are.

相关代码:

最初将组添加到数据库中

Adding group to the database initially:

db = SQLAlchemy(app)
# ...
g = Group(request.form['name'], user_id)
db.session.add(g)
db.session.commit()

Group类:

from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import ARRAY

class Group(db.Model):
    __tablename__ = "groups"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))
    leader = db.Column(db.Integer)

    # list of the members in the group based on user id
    members = db.Column(ARRAY(db.Integer))

    def __init__(self, name, leader):
        self.name = name
        self.leader = leader
        self.members = [leader]

    def __repr__(self):
        return "Name: {}, Leader: {}, Members: {}".format(self.name, self.leader, self.members)

    def add_user(self, user_id):
        self.members += [user_id]

我用于更新网上论坛的测试功能:

My test function for updating the Group:

def add_2_to_group():
    g = Group.query.all()[0]
    g.add_user(2)
    db.session.commit()
    return redirect(url_for('show_groups'))

感谢您的帮助!

推荐答案

正如您提到的,即ARRAY sqlalchemy中的数据类型是不可变的.这意味着初始化后就无法将新数据添加到阵列中.

As you have mentioned, the ARRAY datatype in sqlalchemy is immutable. This means it isn’t possible to add new data into array once it has been initialised.

要解决此问题,请创建类MutableList.

To solve this, create class MutableList.

from sqlalchemy.ext.mutable import Mutable

class MutableList(Mutable, list):
    def append(self, value):
        list.append(self, value)
        self.changed()

    @classmethod
    def coerce(cls, key, value):
        if not isinstance(value, MutableList):
            if isinstance(value, list):
                return MutableList(value)
            return Mutable.coerce(key, value)
        else:
            return value

此代码段允许您扩展列表以增加可变性.因此,现在您可以使用上面的类来创建可变的数组类型,例如:

This snippet allows you to extend a list to add mutability to it. So, now you can use the class above to create a mutable array type like:

class Group(db.Model):
    ...
    members = db.Column(MutableList.as_mutable(ARRAY(db.Integer)))
    ...

这篇关于Flask Postgresql数组无法永久更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆