Hello all,

I'm new to DRF and am attempting to use it to add API features to an 
existing application.  I'm getting the following error with a model that 
has a 1:n relationship with itself:

Could not resolve URL for hyperlinked relationship using view name 
"dockerimage-detail". You may have failed to include the related model in 
your API, or incorrectly configured the `lookup_field` attribute on this 
field.

Here is my setup:

Model:

class DockerImage(models.Model):
    class Meta:
        verbose_name = 'Docker Image'
        verbose_name_plural = 'Docker Images'
        ordering = ('di_name',)

    # 1:n with self
    parent_image = models.ForeignKey(
        'self',
        on_delete=models.PROTECT,
        verbose_name='Parent Image',
        blank=True,
        null=True,
    )

    di_name = models.CharField(
        'Image Name',
        max_length=32,
        unique=True,
        validators=[validate_lower],
    )

    # The last time the image was built
    di_last_built = models.DateTimeField(
        'Last Built',
        blank=True,
        null=True,
    )

    def __str__(self):
        return self.di_name

Serializer:

class DockerImageSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = DockerImage
        fields = ['parent_image', 'di_name', 'di_last_built']

View:

class DockerImageViewSet(viewsets.ModelViewSet):
    queryset = DockerImage.objects.all()
    serializer_class = DockerImageSerializer

URLs:

router = routers.DefaultRouter()
router.register(r'dockerimage', views.DockerImageViewSet)

urlpatterns = [
    url(r'^api/', include(router.urls)),
]

If I remove "parent_image" (the self-1:n) from the field list all works as 
expected.

I've also tried using this as my serializer with no difference:

class DockerImageSerializer(serializers.ModelSerializer):
    parent_image = serializers.HyperlinkedRelatedField(
        read_only=True,
        view_name='dockerimage-detail',
    )

    class Meta:
        model = DockerImage
        fields = ['parent_image', 'di_name', 'di_last_built']

Could someone shed some light as to where I'm going wrong and/or a 
reasonable workaround?

Thanks in advance,

j


-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to