-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
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
PrimaryKeyRelatedField from property method wrongly generates PKOnlyObject #6643
Comments
I'm going to close this off as unintended usage. Related fields are designed to work across ORM relationships, and this is just a regular Python property that happens to look kind of like a relationship. However, all of the ORM metadata that backs these fields is not present (since it's not an actual model field), so naturally the related serializer fields may not work. That said, you should be able to achieve the desired result with the following: class BarSerializer(serializers.ModelSerializer):
foo = serializers.IntegerField(source='foo.pk')
class Meta:
model = Bar
fields = ['id', 'foo'] |
It would be nice if this worked. |
I just hit this too and spent a bunch of time tearing my hair out trying to figure out why. Might be nice if the framework could spit out an error or something when folks make this mistake. |
Checklist
master
branch of Django REST framework.It seems related to PKOnlyObject optimization may break HyperlinkedRelatedField #4653, but that one was closed with no action taken.
Steps to reproduce
Define the following models and serializer:
Create
Bar
instance and attempt to render it:Expected behavior
The serialization and deserialization should behave the same way they would if the field was a real FK in the model, that is, extract the PK from the related object in the serialization, and obtain the related object from the PK in the deserialization.
serializer.data
should beWhich can be rendered to JSON.
Actual behavior
serializer.data
isWhich causes the error in the JSON rendering.
If I understand it correctly, this situation should fall into the edge case handled in
RelatedField.get_attribute()
:but because it is a
@property
method, it does not return a callable and causes the method to assume it is a PK.I tried changing the source to
foo.pk
, that corrects the serialization behaviour, but messes up the deserialization behaviour (which was correct).The text was updated successfully, but these errors were encountered: