我有一个Django项目,我需要根据项目的现有模型创建API REST。我的意思是,是否只能导入api / v1 / models.py中的模型?我需要使用嵌套的序列化程序,但我没有深入了解文档。
我有一个项目" hotel"在项目中,我有各种各样的应用,例如"预订","面板","联系"还有很多。所以,每个应用程序都有模型,视图,网址。
我需要根据每个模型创建API REST。现在我已经用rest-framework创建了一个新的应用程序,名为" api"在模型中我只导入其他应用程序的模型。基本上这是我项目的根源。
hotel/
booking/
__init__.py
views.py
models.py
forms.py
urls.py
panel
contact
api/ (with rest-framework)
__init__.py
models.py
serializers.py
urls.py
views.py
实际上在api中这是结构:
# models.py
from booking.models import ReserveClient, CodeClient, CodeHour
# serializers.py
from rest_framework import serializers
from api.models import CodeClient, CodeHour
class CodeHourSerializer(serializers.ModelSerializer):
class Meta:
model = CodeHour
fields = (
'hours',
'min_hours',
)
class CodeClientSerializer(serializers.ModelSerializer):
class Meta:
model = CodeClient
fields = (
'id',
'code',
'date',
'max_use',
'unique_for_user',
'new_client',
'message',
'comment',
)
# views.py
import django_filters
from api.models import CodeClient, CodeHour
from api.serializers import CodeClientSerializer, CodeHourSerializer
class CodeClientFilter(django_filters.FilterSet):
class Meta:
model = CodeClient
fields = ['code']
class CodeClientList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = CodeClient.objects.all()
serializer_class = CodeClientSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_class = CodeClientFilter
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
好的,现在我想用两个序列化器生成一个视图,因为我需要这样的响应JSON:
[
{
id: 4,
code: "3hours",
date: null,
max_use: 0,
unique_for_user: true,
new_client: true,
menssage: "",
comment: "",
hours: "", (CodeHourSerializer)
min_hours: "", (CodeHourSerializer)
}
]
希望代码更容易理解。
感谢。
古斯塔沃。
答案 0 :(得分:1)
我需要在项目模型上创建API REST
DRF仅为此提供first, _, third = my_tuple
,您只需将其与其中一个模型绑定即可
ModelViewSet
http://www.django-rest-framework.org/api-guide/viewsets/#modelviewset
我需要使用嵌套的序列化程序 您可以执行以下序列化程序:
class MyModelViewSet(viewsets.ModelViewSet):
"""
A viewset for viewing and editing user instances.
"""
serializer_class = MyModelSerializer
queryset = MyModel.objects.all()
http://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization
答案 1 :(得分:0)
不确定您的模型是什么样的,但我认为您只需要在CodeClientSerializer上添加SerializerMethodField。
class CodeClientSerializer(serializers.ModelSerializer):
hours = serializers.SerializerMethodField()
min_hours = serializers.SerializerMethodField()
class Meta:
model = CodeClient
fields = (
...
'hours',
'min_hours',
)
def get_hours(self, obj):
return HOURS # set your value here
def get_min_hours(self, obj):
return MIN_HOURS # set your value here