Skip to content

URLFor and many relationships #194

Description

@retr0h

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'),
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions