【发布时间】:2021-08-12 19:27:41
【问题描述】:
我有这个产品型号
import uuid
from django.db import models
class Product(models.Model):
"""Product in the store."""
title = models.CharField(max_length=120)
description = models.TextField(blank=True)
price = models.DecimalField(decimal_places=2, max_digits=10)
inventory = models.IntegerField(default=0)
uuid = models.UUIDField(default=uuid.uuid4, editable=False)
def __str__(self):
return f'{self.title}'
我为它定义了一个序列化器
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['title', 'description', 'price', 'inventory', 'uuid']
这是我的观点
from rest_framework import viewsets
from .serializers import ProductSerializer
from .models import Product
class ProductViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
lookup_field = 'uuid'
要开始这个问题,请记住此视图路由到/store/products/。
现在,例如,我可以执行 GET http://localhost/store/products/ 并返回
[
{
"title": "Computer",
"description": "",
"price": "50.00",
"inventory": 10,
"uuid": "2d849f18-7dea-42b9-9dac-2ea8a17444c2"
}
]
但我希望它返回类似的东西
[
{
"href": "http://localhost/store/products/2d849f18-7dea-42b9-9dac-2ea8a17444c2"
}
]
然后让http://localhost/store/products/2d849f18-7dea-42b9-9dac-2ea8a17444c2返回
{
"title": "Computer",
"description": "",
"price": "50.00",
"inventory": 10,
"uuid": "2d849f18-7dea-42b9-9dac-2ea8a17444c2"
}
就像它已经做到的那样。这是否可以使用内置序列化,或者我如何定义一个这样做的?我玩过list_serializer_class 属性,但我什么都做不了。
【问题讨论】:
-
您看过关于超链接字段的文档吗? django-rest-framework.org/api-guide/relations/…
-
@TimNyborg 是的,我花了一些时间研究它,但我不明白它如何适合这里。
-
很公平。我将在下面提供一个示例
标签: django django-rest-framework