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

Dynamic serializer fields are not supported #108

Closed
melvinkcx opened this issue Dec 11, 2024 · 4 comments · Fixed by #109
Closed

Dynamic serializer fields are not supported #108

melvinkcx opened this issue Dec 11, 2024 · 4 comments · Fixed by #109

Comments

@melvinkcx
Copy link
Contributor

Hi, I'm trying to use a serializer that adds fields dynamically. However, XLSXRenderer is not able to pick up those fields.

Here's a simple example:

class MySerializer(serializers.Serializer):
    field_1 = serializers.CharField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["dynamic_field_1"] = serializers.CharField(label="Dynamic Field", allow_null=True)

In the output XLSX, only field_1 is included.

I believe the use of serializer.get_fields() is the root cause:

_fields = serializer.get_fields()

The default implementation of get_fields() in BaseSerializer returns self._declared_fields. This can be resolved by referencing to serializer.fields instead.

Let me know what you think. I can create an MR to fix it.

IMO, I think we should update this line to use serializer.fields as well.

https://github.com/django-commons/drf-excel/blob/0d47d7bdfcfbe8d09e6186bfea46f8cdc76e2adc/drf_excel/renderers.py#L156C18-L156C29

@browniebroke
Copy link
Member

Interesting... Didn't know it was a thing, is it something well supported by DRF? I'm wondering if there would be any unintended side effects. If you can make a PR with some good testing, I'll be happy to look into it, yes.

@FlipperPA
Copy link
Member

There's another reference to get_fields() here:

for k, v in serializer.get_fields().items():

We should review and make sure there wouldn't be side-effects there.

@rptmat57
Copy link
Contributor

I thought serializer.fields was already calling get_fields() anyway... but I might be wrong, I haven't looked at that code in a bit.

@melvinkcx
Copy link
Contributor Author

@rptmat57 you're right. serializer.fields is calling get_fields(). However, if extra fields are being added dynamically to serializer.fields in the constructor, get_fields() of the BaseSerializer will not be able to include them. Hence, I think it'd be better to retrieve all fields with serializer.fields rather than serializer.get_fields()

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 a pull request may close this issue.

4 participants