Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Override keyword args for automatically generated serializer fields #99

Merged
merged 3 commits into from
Apr 17, 2024

Conversation

j4mie
Copy link
Member

@j4mie j4mie commented Apr 16, 2024

Fixes #98

This adds optional keyword arguments to the out object (when used as either a decorator or using the >> approach) which are passed to the constructor of the serializer field. This provides a way to add useful attributes to the field (like label and help_text) without throwing away the automagic model introspection behaviour.

class SomeView(SpecMixin, RetrieveAPIView):
    queryset = SomeModel.objects.all()
    spec = [
        ...,
        "title" >> out(label="The title of the object")
        ...,
    ]

Thanks @carltongibson for the API suggestion.

@j4mie
Copy link
Member Author

j4mie commented Apr 16, 2024

Just calling out that this does change an internal API: previously, the serializer field was added to an attribute named out, now we have a generic _readers_annotation dictionary. This is undocumented behaviour so does not require a major version bump.

def out(*args, **kwargs):
if args:
if len(args) != 1:
raise TypeError("Provide a single field or dictionary of fields")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here, it may be worth checking that kwargs are empty too. 🤔

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've decided to explicitly support passing both a field, and also kwargs. See the tests for some examples. I know it's a redundant thing to do (you could just as easily pass the kwargs into the field constructor directly), but it felt more consistent and less surprising to have it "just work"...

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great. No problem 👍

@j4mie j4mie merged commit 5fdd2f1 into main Apr 17, 2024
16 checks passed
@j4mie j4mie deleted the override-serializer-args branch April 17, 2024 11:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Support overriding serializer arguments for automatically generated serializers
3 participants