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.