Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy.exc.ArgumentError: Mapper mapped class could not assemble any primary key columns for mapped table 'users'

I am trying to connect my database. But I couldn't.

My error:

sqlalchemy.exc.ArgumentError: Mapper mapped class User->users could not assemble any primary key columns for mapped table 'users'

Help me guys! here is my code:

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 = "[email protected]"
usr.usr_pass = "123"

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

usrs = User.query.all()

for urr in usrs:
    print(urr)

Here is my table structure:

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)
);
like image 538
Nyamkhuu Buyanjargal Avatar asked Nov 16 '19 15:11

Nyamkhuu Buyanjargal


1 Answers

Remove each comma , in your class User, like below :

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)
like image 164
damadam Avatar answered Oct 26 '22 07:10

damadam