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

Automatic Inclusion of @Property Fields in ModelSerializer #9414

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1111,7 +1111,22 @@ def get_fields(self):

# Create the serializer field.
fields[field_name] = field_class(**field_kwargs)

property_fields = getattr(self.Meta, 'property_fields', None)
if property_fields:
if property_fields == '__all__':
for attr_name in dir(model):
attr = getattr(model, attr_name)
if isinstance(attr, property):
fields[attr_name] = ReadOnlyField()
elif isinstance(property_fields, list) or isinstance(property_fields, tuple):
for attr_name in property_fields:
attr = getattr(model, attr_name, None)
if not attr:
raise ValueError(f"{attr_name} this field doesn't exist in {model} model property")
if isinstance(attr, property):
fields[attr_name] = ReadOnlyField()
else:
raise ValueError("Please select the appropriate value for property_fields in the serializer. Use __all__ to include all property fields, or provide a tuple or list to manually specify the property fields you want to include.")
# Add in any hidden fields.
fields.update(hidden_fields)

Expand Down
Loading