如何在Drf中序列化Hstore字段

时间:2019-03-18 11:48:36

标签: django django-rest-framework hstore

我的模型中有一个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配合使用的参考。但是我没有找到例子。有人有想法或例子吗?

1 个答案:

答案 0 :(得分:0)

我明白了!

我需要将属性设置为JSONField。

我的解决方案:

class CarSerializer(serializers.ModelSerializer):

    attributes = serializers.JSONField()

    class Meta:
        model = Car
        fields = "__all__"