DRF将URL更改为绝对URL

时间:2018-02-27 12:22:54

标签: python django django-rest-framework

我上传了一些文件到服务器,你可以看到地址:

及其故事:

"file": "/upload/user_1/backup.zip",

localhost:8000/upload/user_1/backup.zip",

请告诉我如何将其更改为绝对网址:

class ProductSerializer(ModelSerializer): product_ratings = ProductRatingsSerializer(many=True, read_only=True) product_video = ProductVideoSerializer(many=True, read_only=True) author = serializers.SerializerMethodField() def get_author(self, obj): return obj.author.first_name + ' ' + obj.author.last_name def get_category(self, obj): return obj.category.title class Meta: model = Product fields = [ 'product_id', 'author', 'title', 'mini_description', 'you_learn', 'you_need', 'full_description', 'price', 'video_level', 'video_length', 'created_date', 'updated_date', 'product_ratings', 'product_video' ] read_only_fields = ['product_id', 'created_date', 'updated_date', 'author', 'product_ratings'] def validate_title(self, value): if self.context['request']._request.method == 'POST': qs = Product.objects.filter(title__iexact=value) if self.instance: qs.exclude(pk=self.instance.pk) if qs.exists(): raise serializers.ValidationError("this title is already used") return value

我们在django中有一些函数linke get绝对url我不关心drf

我的序列化程序类:

class ProductVideoSerializer(ModelSerializer):
    class Meta:
        model = ProductVideo
        fields = [
            'product',
            'name',
            'file',
            'video_length',
            'is_free',
        ]

产品视频服务器:

#search

2 个答案:

答案 0 :(得分:1)

生成URL需要将请求上下文传递给序列化程序,例如

ProductSerializer(context={"request":request})

工作,如果你使用ViewSet,这就完成了。否则,代码不知道要使用什么作为主机名,这样就可以手动完成。

file = SerializerMethodField()
def get_file(self, obj):
    return self.context['request'].build_absolute_uri(obj.file.url)

答案 1 :(得分:0)

您可以在SerializerMethodField课程中使用ProductVideoSerializer

class ProductVideoSerializer(ModelSerializer):
    file_abs_url = serializers.SerializerMethodField()

    class Meta:
        model = ProductVideo
        fields = [
            'product',
            'name',
            'file_abs_url',
            'video_length',
            'is_free',
        ]
    def get_file_abs_url(self, obj):
        request = self.context.get('request')
        return request.build_absolute_uri(obj.file.url)