sqlalchemy.exc.ArgumentError:映射器映射的类无法为映射表“用户”组装任何主键列

时间:2019-11-16 15:20:57

标签: python postgresql sqlalchemy flask-sqlalchemy

我正在尝试连接数据库。但是我做不到。

我的错误:

  

sqlalchemy.exc.ArgumentError:映射器映射的类User->用户可以   不能为映射表“用户”组装任何主键列

帮帮我!这是我的代码:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql.base import UUID
from sqlalchemy import text

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:test@localhost/test' 
db = SQLAlchemy(app)
db.UUID = UUID
#User table
class User(db.Model):
    __tablename__ = 'users'
    usr_id = db.Column(UUID(as_uuid=True), primary_key=True, server_default=text("uuid_generate_v4()")),
    usr_name = db.Column(db.String, nullable=False),
    usr_email = db.Column(db.String, nullable=False),
    usr_pass =  db.Column(db.String, nullable=False)

    def __repr__(self):
        return "<User(name='%s', email='%s')>" % (self.usr_name, self.usr_email)

usr = User()

usr.usr_name = "Nyamkhuu"
usr.usr_email = "info@info.com"
usr.usr_pass = "123"

db.session.add(usr)
db.sesion.commit()

usrs = User.query.all()

for urr in usrs:
    print(urr)

这是我的表结构:

create table users (
    usr_id    uuid DEFAULT uuid_generate_v4(),
    usr_name  varchar NOT NULL,
    usr_email varchar NOT NULL,
    usr_pass  varchar NOT NULL,
    PRIMARY KEY(usr_id)
);

1 个答案:

答案 0 :(得分:1)

删除班级,中的每个逗号User,如下所示:

class User(db.Model):
    __tablename__ = 'users'
    usr_id = db.Column(UUID(as_uuid=True), primary_key=True, server_default=text("uuid_generate_v4()"))
    usr_name = db.Column(db.String, nullable=False)
    usr_email = db.Column(db.String, nullable=False)
    usr_pass =  db.Column(db.String, nullable=False)

    def __repr__(self):
        return "<User(name='%s', email='%s')>" % (self.usr_name, self.usr_email)