Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Many to many, Relation and SQLAlchemy association table #137

Open
nbx3 opened this issue Jul 13, 2018 · 1 comment
Open

Many to many, Relation and SQLAlchemy association table #137

nbx3 opened this issue Jul 13, 2018 · 1 comment

Comments

@nbx3
Copy link

nbx3 commented Jul 13, 2018

I'm just trying out potion, i wanted to evaluate many to many options and found issue #26 which mentions a fix in an older version (im using 0.15.0). This however errors with

RuntimeError: Resource named "user" is not registered with the Api it is bound to.

Code example

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import backref
from flask_potion.routes import Relation
from flask_potion import ModelResource, fields, Api

app = Flask(__name__)
db = SQLAlchemy(app)

roles_users = db.Table('roles_users',
                       db.Column(
                           'user_id',
                           db.Integer(),
                           db.ForeignKey('user.id')),
                       db.Column('role_id',
                                 db.Integer(),
                                 db.ForeignKey('role.id')))

class Role(db.Model):

    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))
    users = db.relationship('User', secondary=roles_users,
                           backref=db.backref('roles', lazy='dynamic'))


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    firstname = db.Column(db.String(), nullable=False)
    lastname = db.Column(db.String(), nullable=False)

db.create_all()

class RoleResource(ModelResource):
    users = Relation('user')
    class Meta:
        model = Role

class UserResource(ModelResource):

    class Meta:
        model = User

api = Api(app)
api.add_resource(RoleResource)
api.add_resource(UserResource)

if __name__ == '__main__':
    app.run()
@lyschoening
Copy link
Contributor

Could you try adding the UserResource before adding the RoleResource? For most uses, the Relation() property is unnecessary. I encourage using ToOne fields and filtering on those instead.

http://potion.readthedocs.io/en/latest/quickstart.html#relationships

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants