Repository: encode/django-rest-framework

Issue:
PrimaryKeyRelatedField from property method wrongly generates PKOnlyObject
## Checklist

- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
**It seems related to #4653, but that one was closed with no action taken.**
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)

## Steps to reproduce
Define the following models and serializer:
```python
class Foo(models.Model):
    pass

class Bar(models.Model):
    @property
    def foo(self):
        return Foo.objects.first()

class BarSerializer(serializers.ModelSerializer):
    foo = serializers.PrimaryKeyRelatedField(
        queryset=Foo.objects.all()
    )

    class Meta:
        model = Bar
        fields = ('id', 'foo')
```

Create `Bar` instance and attempt to render it:
```python
>>> Foo.objects.create()
<Foo: Foo object (2)>
>>> bar = Bar.objects.create()
>>> bar.foo
<Foo: Foo object (1)>
>>> serializer = BarSerializer(bar)
>>> serializer.data
{'foo': <Foo: Foo object (1)>, 'id': 2}
>>> JSONRenderer().render(serializer.data)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/clara/.virtualenvs/django_example_project/lib/python3.5/site-packages/rest_framework/renderers.py", line 107, in render
    allow_nan=not self.strict, separators=separators
  File "/home/clara/.virtualenvs/django_example_project/lib/python3.5/site-packages/rest_framework/utils/json.py", line 28, in dumps
    return json.dumps(*args, **kwargs)
  File "/usr/lib/python3.5/json/__init__.py", line 237, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
    return _iterencode(o, 0)
  File "/home/clara/.virtualenvs/django_example_project/lib/python3.5/site-packages/rest_framework/utils/encoders.py", line 68, in default
    return super(JSONEncoder, self).default(obj)
  File "/usr/lib/python3.5/json/encoder.py", line 179, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Foo: Foo object (1)> is not JSON serializable

```
## 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 be
```
{
    'id': 2,
    'foo': 1
}
```
Which can be rendered to JSON.

## Actual behavior

`serializer.data` is
```
{
    'id': 2,
    'foo': <Foo: Foo object (1)>
}
```
Which 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()`:
```python
value = instance.serializable_value(self.source_attrs[-1])
if is_simple_callable(value):
    # Handle edge case where the relationship `source` argument
    # points to a `get_relationship()` method on the model
    value = value().pk
```
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).


Discussion:
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:

```python
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.

Resolving patch:
diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -175,8 +175,13 @@ def get_attribute(self, instance):
                 value = attribute_instance.serializable_value(self.source_attrs[-1])
                 if is_simple_callable(value):
                     # Handle edge case where the relationship `source` argument
-                    # points to a `get_relationship()` method on the model
-                    value = value().pk
+                    # points to a `get_relationship()` method on the model.
+                    value = value()
+
+                # Handle edge case where relationship `source` argument points
+                # to an instance instead of a pk (e.g., a `@property`).
+                value = getattr(value, 'pk', value)
+
                 return PKOnlyObject(pk=value)
             except AttributeError:
                 pass


Test patch:
diff --git a/tests/models.py b/tests/models.py
--- a/tests/models.py
+++ b/tests/models.py
@@ -37,6 +37,15 @@ class ManyToManySource(RESTFrameworkModel):
 class ForeignKeyTarget(RESTFrameworkModel):
     name = models.CharField(max_length=100)
 
+    def get_first_source(self):
+        """Used for testing related field against a callable."""
+        return self.sources.all().order_by('pk')[0]
+
+    @property
+    def first_source(self):
+        """Used for testing related field against a property."""
+        return self.sources.all().order_by('pk')[0]
+
 
 class UUIDForeignKeyTarget(RESTFrameworkModel):
     uuid = models.UUIDField(primary_key=True, default=uuid.uuid4)
diff --git a/tests/test_relations_pk.py b/tests/test_relations_pk.py
--- a/tests/test_relations_pk.py
+++ b/tests/test_relations_pk.py
@@ -30,6 +30,25 @@ class Meta:
         fields = ('id', 'name', 'sources')
 
 
+class ForeignKeyTargetCallableSourceSerializer(serializers.ModelSerializer):
+    first_source = serializers.PrimaryKeyRelatedField(
+        source='get_first_source',
+        read_only=True,
+    )
+
+    class Meta:
+        model = ForeignKeyTarget
+        fields = ('id', 'name', 'first_source')
+
+
+class ForeignKeyTargetPropertySourceSerializer(serializers.ModelSerializer):
+    first_source = serializers.PrimaryKeyRelatedField(read_only=True)
+
+    class Meta:
+        model = ForeignKeyTarget
+        fields = ('id', 'name', 'first_source')
+
+
 class ForeignKeySourceSerializer(serializers.ModelSerializer):
     class Meta:
         model = ForeignKeySource
@@ -389,6 +408,34 @@ class Meta:
         assert len(queryset) == 1
 
 
+class PKRelationTests(TestCase):
+
+    def setUp(self):
+        self.target = ForeignKeyTarget.objects.create(name='target-1')
+        ForeignKeySource.objects.create(name='source-1', target=self.target)
+        ForeignKeySource.objects.create(name='source-2', target=self.target)
+
+    def test_relation_field_callable_source(self):
+        serializer = ForeignKeyTargetCallableSourceSerializer(self.target)
+        expected = {
+            'id': 1,
+            'name': 'target-1',
+            'first_source': 1,
+        }
+        with self.assertNumQueries(1):
+            self.assertEqual(serializer.data, expected)
+
+    def test_relation_field_property_source(self):
+        serializer = ForeignKeyTargetPropertySourceSerializer(self.target)
+        expected = {
+            'id': 1,
+            'name': 'target-1',
+            'first_source': 1,
+        }
+        with self.assertNumQueries(1):
+            self.assertEqual(serializer.data, expected)
+
+
 class PKNullableForeignKeyTests(TestCase):
     def setUp(self):
         target = ForeignKeyTarget(name='target-1')