我有一个主表“PfPersona”,其中包含一个字段“stato_civile”,该字段需要 1 个字符(枚举的“键”)。对于此示例,假设枚举只有一个值。在 DB 中,该值为“S”。枚举的定义正确吗?
class StatoCivile(Enum):
S = "value"
在我的主模型中,我会像这样引用枚举:
stato_civile = models.CharField(StatoCivile,max_length=1, blank=True, null=True, db_column='stato_civile')
在主模型的序列化器中,我已经有许多可扩展字段,它们都可以工作,因为它们有一个实际的 FK。我还尝试添加“stato_civile”以使其可扩展。
expandable_fields = {
"otherfield" : OtherFieldSerializer,
.
.
"stato_civile":StatoCivileSerializer
}
我尝试定义 StatoCivileSerializer
class StatoCivileSerializer(serializers.ModelSerializer):
class Meta:
model = StatoCivile
fields = ['name']#not sure what field I should define
如果我将“stato_civile”作为可扩展字段来调用 URL,如下所示
http://localhost:8000/pf/?expand=stato_civile
我有这个错误
in __getattr__
raise AttributeError(name) from None
AttributeError: _meta
基本上我不明白如何管理枚举,因为我拥有的所有其他可扩展字段都可以工作,这要归功于它们有一个实际的外键。
它抱怨您指定的字段名称不正确。
这是我如何做到这一点的示例:
以下是构建
StatoCivileSerializer
的方法:
serializers.py
from rest_framework import serializers
class StatoCivileSerializer(serializers.ModelSerializer):
stato_civile = serializers.ChoiceField(choices=StatoCivile)
class Meta:
model = StatoCivile
fields = ['stato_civile'] # or "__all__"
要连接串行器,您可以执行以下操作:
api.py
import rest_framework
from rest_framework import viewsets
class ModelNameViewSet(viewsets.ModelViewSet):
http_method_names = ['get']
serializer_class = StatoCivileSerializer
queryset = ModelName.objects.all()
lookup_field = ['stato_civile']
renderer_classes = [rest_framework.renderers.JSONRenderer, rest_framework.renderers.BrowsableAPIRenderer] #The BrowsableAPIRenderer is used to display the API in a browser-friendly format. It is ideal for manual testing directly from the browser.
urls.py
from rest_framework import routers
from drf_yasg.views import get_schema_view
router = routers.DefaultRouter()
router.register(r'name_url', ModelNameViewSet, basename='name_url')
schema_view = get_schema_view(
openapi.Info(
title="RENTAL API",
default_version='v1',
description="Documentation",
),
public=True,
permission_classes=[permissions.AllowAny],
)
urlpatterns = [
path('api/', include(router.urls)),
]
现在您的 API 将可以通过以下链接的过滤器进行访问:
/api/name_url/?stato_civile=s