SQLAlchemy "AttributeError: 'str' object has no attribute 'c'"


WiGeeky:

I have two tables named usersand permissionsI want to create a relationship between them using the specified table userPermissions. Here's what my code looks like:

类User(Base):
    __tablename__ ='用户' 

    id =列(Integer,primary_key = True)
    first_name = Column(Text)
    last_name = Column(Text,nullable = True)

class Permission(Base):
    __tablename__ ='permissions'id 

    =列(Integer,primary_key = True)
    标题=列(String(64))
    allow_anonymous =列(Boolean)

类UserPermission(Base):
    __table__ ='userPermissions'id 

    =列(Integer,primary_key = True)
    user_id =列(Integer, ForeignKey('users.id'))
    Permission_id = Column(Integer,ForeignKey('permissions.id'))
    value = Column(Boolean)

I know I'm probably doing relationships wrong, but searching through documentation and searching I can't find what it is. When I try to create a table with db.Base.metadata.create_all(db.engine)it , I get the following error:

/usr/bin/python3.6 /path/project/out.py
Traceback (most recent call last):
  File "/path/project/out.py", line 1, in <module>
    from components.database import setup
  File "/path/project/components/database/__init__.py", line 41, in <module>
    class UserPermission(Base):
  File "/home/user/.local/lib/python3.6/site-packages/sqlalchemy/ext/declarative/api.py", line 65, in __init__
    _as_declarative(cls, classname, cls.__dict__)
  File "/home/user/.local/lib/python3.6/site-packages/sqlalchemy/ext/declarative/base.py", line 116, in _as_declarative
    _MapperConfig.setup_mapping(cls, classname, dict_)
  File "/home/user/.local/lib/python3.6/site-packages/sqlalchemy/ext/declarative/base.py", line 144, in setup_mapping
    cfg_cls(cls_, classname, dict_)
  File "/home/user/.local/lib/python3.6/site-packages/sqlalchemy/ext/declarative/base.py", line 172, in __init__
    self._setup_table()
  File "/home/user/.local/lib/python3.6/site-packages/sqlalchemy/ext/declarative/base.py", line 481, in _setup_table
    if not table.c.contains_column(c):
AttributeError: 'str' object has no attribute 'c'

where is the problem?

Super Shot:

In your UserPermissionclass you are using the wrong dunder attribute:

__table__ = 'userPermissions'

should:

__tablename__ = 'userPermissions'

SQLAlchemy tries to treat strings 'userPermissions'as Tableobjects.

For the difference between __table__and __tablename__, in most cases you will only need to declare __tablename__ = "stringvalue"a class declaration. It indicates that the object should refer to a table of that name, and SQLAlchemy can handle the construction of that object Tableinternally .

__table__Declaring a on an object signals to SQLAlchemy that you wish to control the construct Tablerepresented by the ORM class . This is useful if you already have references to the table by other means, such as table reflection. Read more here .

Related


SQLAlchemy "AttributeError: 'str' object has no attribute 'c'"

WiGeeky: I have two tables named usersand permissionsI want to create a relationship between them using the specified table userPermissions. Here's what my code looks like: 类User(Base): __tablename__ ='用户' id =列(Integer,primary_key = True) first_

Using OR in SQLAlchemy

JiminyCricket: I looked at the documentation and can't seem to figure out how to do an OR query in SQLAlchemy. I just want to execute this query. SELECT address FROM addressbook WHERE city='boston' AND (lastname='bulger' OR firstname='whitey') should be like

SQLAlchemy "with regular"

Storm Rider I want to translate the following query using SQLAlchemy, but I didn't find anything related to this topic in the documentation. SELECT * FROM table_persons, jsonb_array_elements(data->'persons') WITH ORDINALITY as persons (data, n); where the dat

Validation in SQLAlchemy

James May How can I get the required validator in SQLAlchemy? Actually, I just want to trust that the user fills in all required fields in the form. I use PostgreSQL, but it doesn't make sense because the table created from Objects in my models.py file is: fr

Transactions and SQLAlchemy

Lezan I'm trying to figure out how to insert many (~100k) records into a database using SQLAlchemy in Python 3. Everything points to using transactions. However, I'm a little confused as to how to get the job done. Some countries you get deals from connection.

SQLAlchemy inheritance

Noah: I'm so confused about inheritance under sqlalchemy that I'm not even sure what type of inheritance (single table, joined table, concrete) should I use here. I have a base class that contains some information that is shared between subclasses, and some co

SQLAlchemy IN clause

Wenzback: I am trying to execute this query in sqlalchemy SELECT id, name FROM user WHERE id IN (123, 456) I want to bind the list [123, 456]at execution time . Simon: How session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all() EDIT : Without

Using OR in SQLAlchemy

JiminyCricket: I looked at the documentation and can't seem to figure out how to do an OR query in SQLAlchemy. I just want to execute this query. SELECT address FROM addressbook WHERE city='boston' AND (lastname='bulger' OR firstname='whitey') should be like

SQLAlchemy disconnected

Sidney De Moras I'm wondering if anyone has had this problem before. I have an application running in a Docker container using Python 3.7.3, SqlAlchemy and Falcon. My database is MariaDB, also running in a docker container. I set SqlAlchemy pool_recycleto 3600

SQLAlchemy disconnected

Sidney De Moras I'm wondering if anyone has had this problem before. I have an application running in a Docker container using Python 3.7.3, SqlAlchemy and Falcon. My database is MariaDB, also running in a docker container. I set SqlAlchemy pool_recycleto 3600

SQLAlchemy Relationships

Michael I'm aware ForeignKeyof restricting a column to id values contained in another table so that entries in two different tables can be easily linked, but I don't understand the behavior relationships(). As far as I can tell, the main effect of the relation

Transactions and SQLAlchemy

Lezan I'm trying to figure out how to insert many (in the order of 100k) records into a database using SQLAlchemy in Python 3. However, I'm a little confused as to how to get the job done. Some countries you get deals from connection.begin(), others say it's w

SQLAlchemy update

jackypan1989 I want to create a table from two existing tables in different sessions. E.g: User {uid, fname, lname} Salary {uid, salary} => NewTable {uid, full_name, salary} First I "add" the user to the NewTable and the salary is null -> ok n = NewTable(uid=

Using OR in SQLAlchemy

JiminyCricket: I looked at the documentation and can't seem to figure out how to do an OR query in SQLAlchemy. I just want to execute this query. SELECT address FROM addressbook WHERE city='boston' AND (lastname='bulger' OR firstname='whitey') should be like

SQLAlchemy inheritance

Noah: I'm a little confused about inheritance under sqlalchemy to the point that I'm not even sure which inheritance type I should use here (single table, joined table, specific). I have a base class that contains some information that is shared between subcla

SQLAlchemy IN clause

Wenzback: I am trying to execute this query in sqlalchemy SELECT id, name FROM user WHERE id IN (123, 456) I want to bind the list [123, 456]at execution time . Simon: How about it session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all() EDIT :

GLOB for SQLAlchemy

Duncan WP I'm using SQLAlchemy on a SQLite backend and I want to perform the following updates: UPDATE Measurement SET MeasurementCampaign=? WHERE filename GLOB ? But I can't find any equivalent GLOB function in the SQLAlchemy documentation. I have a lot of w

SQLAlchemy "with regular"

Storm Rider I want to translate the following query using SQLAlchemy, but I didn't find anything related to this topic in the documentation. SELECT * FROM table_persons, jsonb_array_elements(data->'persons') WITH ORDINALITY as persons (data, n); where the dat

select * in sqlAlchemy

Udes I'm struggling to run a select* query in sql alchemy, my table object looks like this, from sqlalchemy import Column, Date, DateTime, Float, Numeric, Index, Integer, MetaData, SmallInteger, String, UnicodeText, Table, Time, text from sqlalchemy.types

Transactions and SQLAlchemy

Lezan I'm trying to figure out how to insert many (in the order of 100k) records into a database using SQLAlchemy in Python 3. However, I'm a little confused as to how to get the job done. Some countries you get deals from connection.begin(), others say it's w

SQLAlchemy inheritance

Noah: I'm a little confused about inheritance under sqlalchemy to the point that I'm not even sure which inheritance type I should use here (single table, joined table, specific). I have a base class that contains some information that is shared between subcla

Using Flask SQLAlchemy models with regular SQLAlchemy

mr pilot I have an existing model written in Flask-SQLAlchemy that cannot be changed. I'm writing another app that uses the same model, but doesn't need Flask, so I'm using the regular SQLAlchemy module. Unfortunately I get a lot: 'AttributeError: Module 'DB'

How to use SQLAlchemy utilities in SQLAlchemy models

Walter I'm trying to create a User model that uses UUID as primary key: from src.db import db # SQLAlchemy instance import sqlalchemy_utils import uuid class User(db.Model): __tablename__ = 'user' id = db.Column(sqlalchemy_utils.UUIDType(binary=Tr

Using Flask SQLAlchemy models with regular SQLAlchemy

mr pilot I have an existing model written in Flask-SQLAlchemy that cannot be changed. I'm writing another app that uses the same model, but doesn't need Flask, so I'm using the regular SQLAlchemy module. Unfortunately I get a lot: 'AttributeError: Module 'DB'

How to use SQLAlchemy utilities in SQLAlchemy models

Walter I'm trying to create a User model that uses UUID as primary key: from src.db import db # SQLAlchemy instance import sqlalchemy_utils import uuid class User(db.Model): __tablename__ = 'user' id = db.Column(sqlalchemy_utils.UUIDType(binary=Tr

Using Flask SQLAlchemy models with regular SQLAlchemy

mr pilot I have an existing model written in Flask-SQLAlchemy that cannot be changed. I'm writing another app that uses the same model, but doesn't need Flask, so I'm using the regular SQLAlchemy module. Unfortunately, I get a lot: 'AttributeError: Module 'DB'

Mock SQLalchemy session for pytest

not me: I don't know if it's possible to do this, but I'm trying to mock db.session.save. I am using flask and flask alchemy. db.py from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() unit test def test_post(self): with app.app_context(): w

sqlalchemy filter by json field

Danila Ganchar : I have models json column. Model and data example: app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://...' db = SQLAlchemy() db.init_app(app) app.app_context().push() class Example(db.Model): id = db.Column(db.Inte