Skip to content

Instantly share code, notes, and snippets.

@multimeric
Created August 6, 2019 07:54
Show Gist options
  • Save multimeric/2e710b50dfccc6cdb348f398627bc0ee to your computer and use it in GitHub Desktop.
Save multimeric/2e710b50dfccc6cdb348f398627bc0ee to your computer and use it in GitHub Desktop.
@multimeric
Copy link
Author

Copied from marshmallow-code/flask-marshmallow#144

You use it like this:

class ReportSchema(ModelSchema):
    samples = ResourceHyperlink(endpoint='rest_api.sample', url_args=[
        'report_id',
        'sample_id'
    ])

Basically you can either provide url_args as a list of keys that we take directly from the related model to apply to the URL (in this case, report_id and sample_id), or you can make that a dictionary that maps URL segments to model properties as I explained above.

I also require that you pass in an endpoint rather than a resource object, just because there will be issues with circular dependencies if you import the resources from the schema and then import the schema in the resources in order to dump/load. The endpoint string for a given resource will be module.path.resource_name, although you can override it with the restful.add_resource() function.

I also recommend that you prefetch the related objects for this field, using query.options(joinedload(user_models.User.roles)), since my class makes use of the related object. If you don't do this, the efficiency will be much worse

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment