-
Notifications
You must be signed in to change notification settings - Fork 23
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
Accessing serializer.fields
inside a nested serializer breaks the use of only/exclude
#52
Comments
Interesting! I quickly just looked at DRF and confirmed my suspicions here based on your comments: @cached_property
def fields(self):
"""
A dictionary of {field_name: field_instance}.
"""
# `fields` is evaluated lazily. We do this to ensure that we don't
# have issues importing modules that use ModelSerializers as fields,
# even if Django's app-loading stage has not yet run.
fields = BindingDict(self)
for key, value in self.get_fields().items():
fields[key] = value
return fields So, looking at this - you can most likely use |
Following up on this, you can use The reason why accessing So while this is really annoying (for me), I'm not sure it's fixable without breaking DRF conventions about when |
Just a question: why do you want to access the fields from within the constructor anyway? Perhaps that might lead us to some conclusion |
I'm applying a permission based filter to (related) field querysets so that the available choices for related objects during a |
Ah I see. And so you're trying to access the nested fields to see if your request user should also have access to those? |
For some reason that I can't quite figure out, it seems that accessing
self.fields
inside a nested and expanded serializer causes theonly/exclude
URL query args to be ignored for that nested serializer (as in I get all fields in the response for any nested serializer that accessesself.fields
inside__init__
).This seems odd to me, and I assume is caused by some side-effect of the field binding that
rest_framework
does whenself.fields
is accessed. I've, so far, managed to implement work arounds that either useextra_kwargs
orself.get_fields()
but many examples/stack-overflow answers suggest usingself.fields
(e.g. to override the widget used for a field in the automatically generated create/update form in the browsable API).Accessing
self.fields
in__init__
of the top level serializer doesn't breakonly/exclude
The text was updated successfully, but these errors were encountered: