我正在嘗試在 Django rest 框架中為我的電子商務應用程式創建產品模型,并且我能夠在管理面板上將影像上傳到我的產品,但是在呼叫 API 時我無法獲取它們的鏈接。這是我的:
模型.py
from django.db import models
from api.category.models import Category
from api.color.models import Color
from api.size.models import Size
class Product(models.Model):
name = models.CharField(max_length=50)
description = models.CharField(max_length=250)
regular_price = models.CharField(max_length=50)
sell_price = models.CharField(max_length=50, blank=True, null=True)
stock = models.CharField(max_length=50)
is_active = models.BooleanField(default=True, blank=True)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True)
colors = models.ManyToManyField(Color)
sizes = models.ManyToManyField(Size)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self) -> str:
return self.name
class ProductImage(models.Model):
product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE)
image = models.FileField(upload_to = 'images/')
def __str__(self):
return self.image.url
序列化程式.py
from django.db.models import fields
from rest_framework import serializers
from .models import Product, ProductImage
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = ProductImage
fields = ('image', )
#print(model)
class ProductSerializer(serializers.HyperlinkedModelSerializer):
colors = serializers.StringRelatedField(many=True)
sizes = serializers.StringRelatedField(many=True)
image = ImageSerializer(many=True, read_only=True)
class Meta:
model = Product
fields = ('id', 'name', 'description', 'regular_price', 'sell_price', 'category','colors', 'sizes', 'image')
管理檔案
from django.contrib import admin
from .models import Product, ProductImage
class ProductImageAdmin(admin.StackedInline):
model = ProductImage
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
inlines = [ProductImageAdmin]
class Meta:
model = Product
@admin.register(ProductImage)
class ProductImageAdmin(admin.ModelAdmin):
pass
查看.py
from rest_framework import viewsets
from .serializers import Product, ProductSerializer, ImageSerializer
from .models import Product, ProductImage
from . import serializers
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all().order_by('id')
serializer_class = ProductSerializer
網址.py
from rest_framework import routers
from django.urls import path, include
from . import views
router = routers.DefaultRouter()
router.register(r'', views.ProductViewSet)
urlpatterns = [
path('', include(router.urls))
]
這是管理面板上的樣子。


但是在呼叫 API 時我無法獲取影像的鏈接,如下圖所示。

uj5u.com熱心網友回復:
首先更新您的ProductImage模型:為此關系添加相關名稱
class ProductImage(models.Model):
...
product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE, related_name="product_images")
將您的序列化程式更改為:
class ProductSerializer(serializers.HyperlinkedModelSerializer):
colors = serializers.StringRelatedField(many=True)
sizes = serializers.StringRelatedField(many=True)
images = serializers.SerializerMethodField()
def get_images(self, product):
return ImageSerializer(product.product_images.all(), many=True).data
class Meta:
model = Product
fields = ('id',..., 'images')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/381154.html
