Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a foreignkey reference with sqlalchemy

Hi I am not able to understand how to make a foreignkey reference using sqlalchemy. I have created a new table client in my database:

class Client(DeclarativeBase):

    __tablename__ = 'client'

    id = Column(Integer, primary_key=True)

    user_id = Column(
        Integer,
        ForeignKey('user.id', ondelete='CASCADE'),
        nullable=False,
        index=True,
    )

    orgname = Column(Unicode, nullable=False)

    def __init__(self, **kwargs):
        super(Client, self).__init__(**kwargs)

Not I am trying to do something like this

 u = User(user_name=u'dusual')
 session.add(u)
 c = Client(user=u, orgname="dummy_org")
 session.add(c)

But sqlalchemy shouts back saying :

(k, cls_.name)) TypeError: 'user' is an invalid keyword argument for Client

Now shouldn't this be obvious that user should be allowed as a keyword argument how can I make sure my table is able to take user keyword argument.

like image 518
dusual Avatar asked Jun 26 '13 16:06

dusual


People also ask

How do I create a composite key in SQLAlchemy?

To create a composite primary key, set primary_key to True on each column involved in the key. A boolean argument when set to False adds NOT NULL constraint while creating a column. Its default value is True .

How does SQLAlchemy define foreign key in Flask?

First you need to supply a Primary Key for each model. Then you need to define one Foreign Key which refers to the Primary Key of the other model. Now you can define a relationship with a backref that allows direct access to the related model. In this case, the following 2 lines should look like this: request_id = db.

What is foreign key in SQLAlchemy?

A foreign key in SQL is a table-level construct that constrains one or more columns in that table to only allow values that are present in a different set of columns, typically but not always located on a different table.


1 Answers

You need to define a relationship between User and Client models:

from sqlalchemy.orm import relationship

class Client(DeclarativeBase):

    __tablename__ = 'client'

    id = Column(Integer, primary_key=True)

    user_id = Column(
        Integer,
        ForeignKey('user.id', ondelete='CASCADE'),
        nullable=False,
        # no need to add index=True, all FKs have indexes
    )
    user = relationship('User', backref='clients')

    orgname = Column(Unicode, nullable=False)

    # no need to add a constructor 

Then you can associate instances of User and Client models in two ways - either by assigning an integer to Client.user_id:

u = User(user_name=u'dusual')
session.add(u)
session.flush()  # to make sure the id is fetched from the database
c = Client(user_id=u.id, orgname="dummy_org")
session.add(c)

or by assinging a User instance to Client.user.

u = User(user_name=u'dusual')
# no need to flush, no need to add `u` to the session because sqlalchemy becomes aware of the object once we assign it to c.user
c = Client(user=u, orgname="dummy_org")
session.add(c)

Actually, there's a third way - since we've configured a backref on Client.user, SQLAlchemy added a list-like clients attribute to our User model:

u = User(user_name=u'dusual')
u.clients.append(Client(orgname="dummy_org"))
session.add(u)
like image 140
Sergey Avatar answered Sep 27 '22 15:09

Sergey