django-rest-framework-json-api icon indicating copy to clipboard operation
django-rest-framework-json-api copied to clipboard

Support for custom hyperlinked related field

Open hmpf opened this issue 6 years ago • 5 comments

I need to be able to add links to read-only resources into the relationships-object of a resource as easily as adding a non-link field with SerializerMethodField. (Generating the link with SerializerMethodField is trivially easy, but they are links.) In all cases so far I can generate the link from data in the object.

Is this supposed to be possible at all or is it just poorly documented?

I've tried non-model serializers, ResourceRelatedField, HyperlinkedRelatedField, and I'm now at the stage where the code is running under pdb in an attempt to figure out how things are supposed to work. It seems such a straightforward, obvious thing to do.

I'm talking about things like this:

class Some(Model):
  data = models.CharField()

class SomeSerializer(serializers.ModelSerializer):
   extra = serializers.SomethingMagicField()

  class Meta:
    model = Some
    fields = ['data','extra']

  def extra(self, obj):
    return 'other_url/{}/'.format(obj.pk)

leading to

{
  "data": {
    "type": "Some",
    "id": "1",
    "attributes": {
       "data": "foo",
    },
    "relationships": {
      "extra": {
        "links": {
          "related": "other_url/1/"
        }
      }
    }
  }
}

instead of

{
  "data": {
    "type": "Some",
    "id": "1",
    "attributes": {
       "data": "foo",
       "extra": "other_url/1/"
    }
  }
}

hmpf avatar Nov 11 '19 09:11 hmpf

Could SerializerMethodResourceRelatedField be what you are looking for? Otherwise in the same file linked above there are many other examples.

sliverc avatar Nov 14 '19 13:11 sliverc

SerializerMethodResourceRelatedField assumes a model and a view name. SerializerMethodField does not assume anything except getting an obj passed in.

hmpf avatar Nov 14 '19 13:11 hmpf

I am not 100% certain but when looking at the code it should work without passing on a model. However I am not sure why you do not want to pass on a view name. Are you trying to link to a different service than DJA is running on?

sliverc avatar Nov 14 '19 14:11 sliverc

Yep. My service has info and metadata about other services. There's also worklng around/hiding some (SQL) modelling details.

hmpf avatar Nov 14 '19 14:11 hmpf

No this is currently not possible. I had a quick look at the renderer and I do not see a quick workaround either to override the url of a relationship from the client code.

A new field would need to be created and the renderer changed to be aware of it.

sliverc avatar Nov 14 '19 14:11 sliverc