Django Rest Framework超链接序列化程序用于具有指向一个特定相关对象的属性的模型?

时间:2015-12-13 23:33:21

标签: django django-rest-framework

在Django Rest Framework中,为具有指向反向相关对象或无的属性的模型编写超链接序列化程序的适当方法是什么?

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)

我们如何为AModel编写一个序列化程序,其中包含属性null的url(或current_another_model}?

我已尝试过此操作(我有一个有效的AnotherModel序列化程序和视图):

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

这让我有这个错误:

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.

1 个答案:

答案 0 :(得分:-1)

定义AnotherModel序列化程序并在AModelSerializer中定义该依赖项,同时在AModelSerializer中添加类Meta。

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

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

该代码应该为您解决问题。

另一种方法是在定义相关序列化程序时坚持官方documentation

更新:发现非常相似的问题Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail"  这已经解决了。