簡體   English   中英

如何在 Django Rest 框架中將數組序列化為字符串?

[英]How to serialize an array to a string in Django Rest Framework?

在使用 Django 構建的網站中,我有一個 model ,它有一個CharField

class Person(models.Model):
    name = models.CharField(max_length=255)
    age = models.IntegerField()
    categories = models.CharField(max_length=255)

CharField 可以包含以逗號分隔的字符串列表。 例如: ADC,HJD,RTP

使用Django Rest 框架,我創建了一個 POST 端點,人們可以向其發布新記錄。 不過,該字段作為數組發布在 json 中。 所以 json 看起來像這樣:

{
    "name": "John",
    "age": 25,
    "categories": ["ADC", "HJD", "RTP"]
}

我想在Serializer create()方法中簡單地join()數組。 但它永遠不會達到那個點,因為它被驗證器過濾掉了。 我猜驗證是在視圖中完成的,但我不確定從哪里開始挖掘。

有誰知道我如何讓端點接受一個數組並將其轉換為 CharField 中的逗號分隔字符串?

[編輯]

這些是我的視圖集:

class DevicesViewSet(DatapuntViewSetWritable):
    queryset = Device.objects.all().select_related('owner', 'contact').prefetch_related('types').order_by('id')

    serializer_class = DeviceSerializer
    serializer_detail_class = DeviceSerializer

    http_method_names = ['post', 'list', 'get']


class ContactViewSet(CreateModelMixin, GenericViewSet):
    queryset = Device.objects.none()
    serializer_class = IotContactSerializer
    pagination_class = None

根據已編輯的問題,您可以執行以下操作。 在您的視圖中繼承 viewsets.ViewSet 並覆蓋 create 方法並編寫您的連接邏輯。 在這里檢查

class CreatePersonViewSet (viewsets.ViewSet):
    def create(self, request):
         """
         Do your logic here... to create
         """
         pass

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM