0

In Django Rest Framework, what's the appropriate way to write a hyperlinked serializer for a model that has a property that points to a reverse related object or None?

class AModel(models.Model):
    a_name = models.CharField()

    @property
    def current_another_model(self):
        # Just an example, could be whatever code that returns an instance
        # of ``AnotherModel`` that is related to this instance of ``AModel``
        try:
            return self.another_model_set.objects.get(blah=7)
        except AnotherModel.DoesNotExist:
            return

class AnotherModel(models.Model):
    blah = models.IntegerField()
    our_model = models.ForeignKey(AModel)

How do we write a serializer for AModel that contains the url (or null, of course) for the property current_another_model?

I've tried this (I have a working AnotherModel serializer and view):

class AModelSerializer(serializers.HyperlinkedModelSerializer):
    current_another_model = serializers.HyperlinkedRelatedField(read_only=True, view_name='another-model-detail', allow_null=True)

That gets me this error:

django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "another-model-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
Dustin Wyatt
  • 4,046
  • 5
  • 31
  • 60

1 Answers1

-1

Define AnotherModel serializer and define that dependency within AModelSerializer, also add class Meta in your AModelSerializer.

class AModelSerializer(serializers.ModelSerializer):
    current_another_model = AnotherModelSerializer(allow_null=True, required=False)

    class Meta:
        model = AModel
        fields = ('current_another_model',)

That code should do the trick for you.

Another way is stick to the official documentation while defining related serializers.

Update: Found quite similar question Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail" which is solved.

Community
  • 1
  • 1
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
  • Almost. This nests the serialized relation, whereas what I'm looking for is the hyperlink. – Dustin Wyatt Dec 13 '15 at 23:48
  • As for your update: As I mention in the question detail, I do have a working serializer and view for the related object so the accepted answer on that question is not applicable. – Dustin Wyatt Dec 14 '15 at 00:06