一、在settings中设置media
# settings.py
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
二、在项目总的路由下添加图片路由
# urls.py
from django.urls import path, re_path
from django.conf.urls.static import serve
from 项目 import settings
urlpatterns = [
re_path(r"^media/(?P<path>.*)$", serve, {'document_root': settings.MEDIA_ROOT})
]
# 注意: 必须加上$结尾
三、在创建序列化器
#serializers.py
from rest_framework import serializers
class ProductListSerializers(serializers.Serializer):
"""
商品
"""
...
products_front_image = serializers.ImageField(required=True, use_url=True)
# 在序列化器中的ImageField字段添加上use_url=True,使用url
四、在views文件中调用序列化器
# views.py
from .models import Products
from rest_framework.views import APIView
from rest_framework.response import Response
class ProductsList(APIView):
def get(self, request, *args, **kwargs):
key_id = request.GET.get('id')
print(key_id)
products = Products.objects.filter(id=key_id)
serializers = ProductListSerializers(products,
many=True,
context={"request": request})
return Response(serializers.data)
# 在调用序列化器时传入参数context={"request": request},如果想要图片加上url,必须传入该参数
'''请求结果'''
[
{
"name": "自营高档茶叶礼盒定制款(包邮)",
"description": "高档商品",
"click_num": 0,
"sold_num": 0,
"fav_num": 0,
"products_num": 0,
"market_price": 598.0,
"shop_price": 299.0,
"products_front_image": "http://localhost:8000/media/products/tea-gift-customized01.png"
}
]