Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Getting resource_name dynamically #935

Adman started this conversation in General
Apr 22, 2021 · 1 comments · 2 replies
Discussion options

I have the following structure of serializers

class A(Serializer)
 class JSONAPIMeta:
 resource_name = "A"
class B(Serializer)
 class JSONAPIMeta:
 resource_name = "B"
class MySerializer(Serializer)
 my_field = OneOfSerializer(A(), B())

OneOfSerializer is my custom serializer accepting values either for A or B. The main problem is that it doesn't contain JSONAPIMeta and DRF-jsonapi raises an exception. Would it be possible to somehow return the resource_name dynamically based on the data, so that the relation is correctly set?

You must be logged in to vote

Replies: 1 comment 2 replies

Comment options

What version of DJA are you using? Since DJA version 4.0.0 nested serializers are not rendered as relationships anymore but as attribute value. So when I look at your example this would actually be rendered as attribute value instead and resource name is not needed in this case.

But if you wanna have dynamic relationships you can use SerializerMethodResourceRelatedField and the resource name is then calculated by the returning instance.

Does this help? Or have I misunderstood your question?

You must be logged in to vote
2 replies
Comment options

I'm using version 3.1.0.
Is the SerializerMethodResourceField going to work for serializer which is not tied to a model? I mean, I'm initializing it with custom data not necessarily being taken from django model. I'll try to experiment with that.

Comment options

Yes it should work but give it a try.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #931 on April 29, 2021 19:20.

AltStyle によって変換されたページ (->オリジナル) /