如何序列化 drf 中的 Hstore 字段

How to serialize a Hstore field in drf

我的模型中有一个 HStoreField。示例:

attributes = HStoreField(default=dict, blank=True)

我的视图和序列化器:

class CarSerializer(serializers.ModelSerializer):

    class Meta:
        model = Car
        fields = "__all__"
class CarViewSet(viewsets.ModelViewSet):
    queryset = Car.objects.all()
    serializer_class = CarSerializer
    model = Car

好的。当我尝试一些测试时,像这样:

@pytest.fixture
def create_car(client):
    response = client.post(
        '/myapi/v1/car/',
        data={
            'name': "Ford Mustang",
            'price': 2000,
            'attributes': {"key": "value"},
        },
        format='json',
    )
    return response

@pytest.mark.django_db
def test_car_view(client, create_car):
    response = create_car
    response_get = client.get(f'/myapi/v1/car/{response.data["id"]}/')
    assert response_get.status_code == 200

我收到此错误:

self = HStoreField(required=False), value = '"key"=>NULL'

    def to_representation(self, value):
        """
        List of object instances -> List of dicts of primitive datatypes.
        """
        return {
            six.text_type(key): self.child.to_representation(val) if val is not None else None
>           for key, val in value.items()
        }
E       AttributeError: 'str' object has no attribute 'items'

在查找有关此问题的信息时,我找到了使用 DictField 来处理 HStoreField 的参考资料。但是我没有找到例子。有人有想法或例子吗?

我明白了!

我需要将属性设置为 JSONField。

我的解决方案:

class CarSerializer(serializers.ModelSerializer):

    attributes = serializers.JSONField()

    class Meta:
        model = Car
        fields = "__all__"