marshmallow-code / marshmallow-code/flask-marshmallow

URLFor and many relationships

Open
#194 0 comments 2 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
887
Forks
65
Avg merge
7h 25m
Merged PRs (30d)
3

Description

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='',
#),
'collection': ma.URLFor('lease_v1_bp.get_leases'),
}
```

Contributor guide

Open the contributing guide

Research direction

Start with the LeaseSchema definition, especially the nested resources field and the commented ma.URLFor configuration, then trace how the lease_v1_bp endpoint receives URL parameters. Determine whether URLFor supports deriving a discriminator from a list relationship, and document or implement a clear supported approach whose generated self URL matches the requested resource.

Written by the indexing model from the issue text.

Assessment

Tech stack
flask, python, sqlalchemy
Domain
api, backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.