最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

serialization - Django: how to "expand" a field which references an enum but not another table - Stack Overflo

programmeradmin1浏览0评论

I have a main table "PfPersona" with a field "stato_civile" that takes 1 char (the "key" of an enum). For this example let's say the enum has only one value. In DB the value would be "S". Is the definition of the enum correct?

class StatoCivile(Enum):
     S = "value"

And in my main model I would reference the enum like this:

stato_civile = models.CharField(StatoCivile,max_length=1, blank=True, null=True, db_column='stato_civile')

In the serializer of the main model I already have many expandable fields and they all work because they have an actual FK. I tried to put also "stato_civile" to make it expandable.

expandable_fields = {
        "otherfield" : OtherFieldSerializer,
        .
        .
        "stato_civile":StatoCivileSerializer
    }

I tried to define the StatoCivileSerializer

class StatoCivileSerializer(serializers.ModelSerializer):

class Meta:
    model = StatoCivile
    fields = ['name']#not sure what field I should define

If I call the URL with "stato_civile" as an expandable field like this

http://localhost:8000/pf/?expand=stato_civile

I have this error

in __getattr__
raise AttributeError(name) from None
AttributeError: _meta

Basically I didn't understand how to manage Enums because all the other expandable fields I have work thanks to the fact that they have an actual ForeignKey.

I have a main table "PfPersona" with a field "stato_civile" that takes 1 char (the "key" of an enum). For this example let's say the enum has only one value. In DB the value would be "S". Is the definition of the enum correct?

class StatoCivile(Enum):
     S = "value"

And in my main model I would reference the enum like this:

stato_civile = models.CharField(StatoCivile,max_length=1, blank=True, null=True, db_column='stato_civile')

In the serializer of the main model I already have many expandable fields and they all work because they have an actual FK. I tried to put also "stato_civile" to make it expandable.

expandable_fields = {
        "otherfield" : OtherFieldSerializer,
        .
        .
        "stato_civile":StatoCivileSerializer
    }

I tried to define the StatoCivileSerializer

class StatoCivileSerializer(serializers.ModelSerializer):

class Meta:
    model = StatoCivile
    fields = ['name']#not sure what field I should define

If I call the URL with "stato_civile" as an expandable field like this

http://localhost:8000/pf/?expand=stato_civile

I have this error

in __getattr__
raise AttributeError(name) from None
AttributeError: _meta

Basically I didn't understand how to manage Enums because all the other expandable fields I have work thanks to the fact that they have an actual ForeignKey.

Share Improve this question asked Nov 20, 2024 at 9:06 Andrea BalestriAndrea Balestri 112 bronze badges 1
  • class StatoCivile is an Enum and not a Django model meaning built-in serializers don't work. You can read more about it here and here – Victor Commented Nov 20, 2024 at 9:08
Add a comment  | 

1 Answer 1

Reset to default 0

It complains that you specified the field name incorrectly.

Here’s an example of how I would do it:

Here's how you can structure the 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__"

To connect the serializer, you can do something like this:

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)),
]

Now your API will be accessible with a filter at the following link: /api/name_url/?stato_civile=s

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论