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

URLFor and many relationships #194

Open
retr0h opened this issue Jun 19, 2020 · 0 comments
Open

URLFor and many relationships #194

retr0h opened this issue Jun 19, 2020 · 0 comments

Comments

@retr0h
Copy link

retr0h commented Jun 19, 2020

I haven't found much luck with the following.

I'd like to use URLFor to describe a URL for a relationship. I am rendering the child model Lease, which back_populates resources.

When I am deserializing the Lease object and links is generated, the parent Resource object is desereialized as well, but since it is a list, I am unsure how I can use that relationship to generate a URL to self, which requires looking at lease.relationships[0].discriminator. See LeaseSchema at bottom.

Resource Model

class Resource(base_mixin.BaseMixin, db.Base):
    __tablename__ = 'resources'

    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    name = sqlalchemy.Column(sqlalchemy.String(32), unique=True)
    labels = sqlalchemy.Column(sqlalchemy.dialects.postgresql.JSONB)

    lease_id = sqlalchemy.Column(
        sqlalchemy.Integer, sqlalchemy.ForeignKey('leases.id')
    )
    lease = sqlalchemy.orm.relationship('Lease', back_populates='resources')

    discriminator = sqlalchemy.Column('type', sqlalchemy.String(50))

    __mapper_args__ = {'polymorphic_on': discriminator}

Sapro Model

class Sapro(resource.Resource):
    __mapper_args__ = {
        'polymorphic_identity': 'sapro',
    }

    def __init__(self, *args, **kwargs):
        super(Sapro, self).__init__(*args, **kwargs)

Lease Model

class Lease(base_mixin.BaseMixin, db.Base):
    __tablename__ = 'leases'
    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)

    resources = sqlalchemy.orm.relationship(
        'Resource', back_populates='lease', cascade='all,delete'
    )

Lease Schema

class LeaseSchema(ma.Schema):
    class Meta:
        fields = (
            'created_at',
            'updated_at',
            'id',
            'resources',
            'links',
        )

    resources = marshmallow.fields.Nested(sapro.SaproSchema)
    links = ma.Hyperlinks(
        {
            # Unsure how to pass the discriminator from resources to URLFor.
            #'self': ma.URLFor(
            #    'lease_v1_bp.test_get_leases_by_discriminator',
            #    resources='<resources>',
            #),
            'collection': ma.URLFor('lease_v1_bp.get_leases'),
        }
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

1 participant