Django Rest Framework获得一个查找字段作为超链接列表

时间:2018-12-12 21:02:44

标签: python django django-rest-framework

我有一个模型相册和一个模型照片,它们通过 FireignKey 字段引用了第一个模型。我希望模型相册 ModelSerializer 返回一个超链接列表,以通过查找字段关联模型照片中的条目,但我只能得到它返回ID列表。

这些是我的模特:

class Album(models.Model):
    name = models.CharField(max_length=200, verbose_name=_("Name"))
    description = models.TextField(null=True, blank=True, verbose_name=_("Description"))
    company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name='albums', verbose_name=_("Company"))
    access_code = models.CharField(max_length=30, default=_create_access_code, verbose_name=_("Internal Use"))

    class Meta:
        verbose_name = _("Album")
        verbose_name_plural = _("Albums")

    def __str__(self):
        return "[{}] {} ({})".format(self.pk, self.name, self.company.id)

class Photo(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True, verbose_name=_("Name"))
    album = models.ForeignKey(Album, on_delete=models.PROTECT, related_name='photos', verbose_name=_("Album"))
    photo = models.ImageField(verbose_name=_("Photo"))

    class Meta:
        verbose_name = _("Photo")
        verbose_name_plural =_("Photos")

    def __str__(self):
        return "[{}] {}".format(self.pk, self.name)

这是我的序列化器:

class AlbumSerializer(serializers.ModelSerializer):
    class Meta:
        model = proxies.AlbumProxy
        fields = ('id', 'name', 'description', 'company', 'access_code', 'photos')

我希望字段photos返回一个超链接列表,但我得到一个ID列表:

"id": 1,
"name": "Navidad 2018",
"description": "La primera",
"company": 1,
"access_code": "xxxxxxxxxx",
"photos": [
     11,
     10,
      7,
      6
]

2 个答案:

答案 0 :(得分:1)

我认为您需要一个HyperlinkedRelatedField,如下所示:

class AlbumSerializer(serializers.ModelSerializer):
    class Meta:
        model = proxies.AlbumProxy
        fields = (
            'id', 
            'name', 
            'description', 
            'company', 
            'access_code',  
            'photos'
        )

    photos = serializers.HyperlinkedRelatedField(
        many=True, 
        view_name='<your-photos-view-name>', 
        read_only=True
    )

答案 1 :(得分:0)

如果您希望自己的photos full urls,可以声明Serializer Method Field来执行以下操作:

class AlbumSerializer(serializers.ModelSerializer):
    photos_url = serializers.SerializerMethodField()

    class Meta:
        model = proxies.AlbumProxy
        fields = ('id', 'name', 'description', 'company', 'access_code')

    def get_photos_url(self, obj):
        urls = []
        request = self.context.get('request')
        for photo in obj.photos:
            urls.append(request.build_absolute_uri(photo.url))
        return urls