I have an HStoreField in my model. Example:
attributes = HStoreField(default=dict, blank=True)
My view and serializer:
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = "__all__"
class CarViewSet(viewsets.ModelViewSet):
queryset = Car.objects.all()
serializer_class = CarSerializer
model = Car
Ok. When I try some tests, like this:
@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
I receive this error:
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'
Looking for information about this problem I found references to use DictField for working with HStoreField. But I did not find examples. Does someone have an idea or examples?
I got it!
I needed to set attributes as a JSONField.
My solution:
class CarSerializer(serializers.ModelSerializer):
attributes = serializers.JSONField()
class Meta:
model = Car
fields = "__all__"