djangodjango-rest-frameworkdjango-serializerdjango-1.8

Django Rest Framework: Add hyperlink related field on sub model


Im trying to find out how I can add hyperlink related field from a relationship model.

Lets say i have the following models:

class Model1(models.Model):
    id = models.AutoField(primary_key=True)
    model2 = models.OneToOneField(Model2, db_column='model2_id', related_name='model2_set', on_delete=CASCADE)
    
class Model2(models.Model):
    id = models.AutoField(primary_key=True)
    model3 = models.ForeignKey(Model3, db_column='model3_id',
        related_name='+', null=True, blank=True, on_delete=FOREIGNKEY_PROTECT)
    
class Model3(models.Model):
    id = models.AutoField(primary_key=True)
    description = models.TextField(db_column='description', null=True, blank=True, verbose_name=_('Description'))

and I have a serializer for both Model1 and Model3 but not Model2

I want to have the following output

{
    "id":123,
    "model3":"http://example:123/api/model3/123"
} 

but in my model1 serializer i cant simply call a hyperlinkrelated field for a sub model because it cannot identify the source

class Model1ListSerializer(ValidateByModelSerializer):
    id = serializers.IntegerField(read_only=True)
    model3 = serializers.HyperlinkedRelatedField(
            source='model2__model3',
            queryset=Model3.objects.all(),
            view_name='model3_rest-detail'
         )

Whats the best way to achieve this?


Solution

  • As source you can make use of model2.model3 to access the object of that ForeignKey:

    class Model1ListSerializer(ValidateByModelSerializer):
        id = serializers.IntegerField(read_only=True)
        model3 = serializers.HyperlinkedRelatedField(
            source='model2.model3',
            queryset=Model3.objects.all(),
            view_name='model3_rest-detail'
         )

    I would advise to also select the related models in the same query, so use this with:

    Model1.objects.select_related('model2', 'model2__model3')