Django 如何在drf中序列化Hstore字段
我的模型中有一个HStoreField。例如:Django 如何在drf中序列化Hstore字段,django,django-rest-framework,hstore,Django,Django Rest Framework,Hstore,我的模型中有一个HStoreField。例如: attributes = HStoreField(default=dict, blank=True) 我的视图和序列化程序: class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = "__all__" 嗯。当我尝试一些测试时,例如: @pytest.fixture def create_car(
attributes = HStoreField(default=dict, blank=True)
我的视图和序列化程序:
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = "__all__"
嗯。当我尝试一些测试时,例如:
@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__"
你能展示一个你正在发布的示例数据吗Hello@Exprator我把我的帖子作为例子。谢谢你,谢谢你的回答。
class CarSerializer(serializers.ModelSerializer):
attributes = serializers.JSONField()
class Meta:
model = Car
fields = "__all__"