-
Notifications
You must be signed in to change notification settings - Fork 301
Unable to render regular Serializer (missing PK) #1126
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
Comments
A temporary workaround is to wrap the dictionary passed to the serializer in an object that proxies the from typing import Any
# See https://github.com/django-json-api/django-rest-framework-json-api/issues/1126
class SerializerResult(dict):
"""The result of a non-model serializer to workaround DJA expecting a `pk` attr."""
def __init__(self, other: dict | None = None, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.update(other)
@property
def pk(self) -> Any | None:
return self.get("id", self.get("pk", None)) Then use it like so - return Response(
self.get_serializer(
SerializerResult(
{
# ...
}
)
)
) References: The class used in the tests. django-rest-framework-json-api/tests/test_views.py Lines 190 to 197 in 735ce29
|
dict
object has no attribute pk
Thanks for bring awareness for this issue again and working on it. See my #1127 (comment) to see how we can go from here. |
It appears that the JSON renderer expects every serializer to be a
ModelSerializer
, preventing regularSerializer
use without a model.Reproduction:
Stacktrace:
Suspected code:
django-rest-framework-json-api/rest_framework_json_api/renderers.py
Lines 460 to 467 in 735ce29
Suggestion:
The text was updated successfully, but these errors were encountered: