Sin5k4
Sin5k4

Reputation: 1626

Using 1-N Relationships with SQLAlchemy

After defining a simple 1-n relation with the following classes:

class User(db.Model):
__tablename__ = 'user'
UserID = db.Column(db.Integer, primary_key=True)
Name = db.Column(db.String(80), unique=True)
emails = db.relationship('email')

def __init__(self, username):
    self.Name = username


class Email(db.Model):
    __tablename__ = 'email'
    EmailID = db.Column(db.Integer, primary_key=True)
    Email = db.Column(db.String(80), unique=True)
    User = db.Column(db.Integer,db.ForeignKey('user.UserID'))

    def __init__(self, mail):
    self.Email = mail

I want to create a user and add it some mails then save it to the db using:

username = "serkan1"
newuser = User(username)
newuser.emails[Email(Email='[email protected]'),Email(Email = '[email protected]')]
db.session.add(product)
db.session.commit()
return "ok"

But i get the error:

ArgumentError: relationship 'emails' expects a class or a mapper argument (received: <class 'sqlalchemy.sql.schema.Table'>)

How can i simply create a user,add it some emails with 1-n schema and save it to the db?

Upvotes: 1

Views: 2500

Answers (1)

Jeremy Allen
Jeremy Allen

Reputation: 6614

Try changing this line:

emails = db.relationship('email')

to:

emails = db.relationship('Email')

Which will reference your Email class instead of your email table as the error message describes.

Upvotes: 5

Related Questions