Reputation: 2000
I have a very basic django view and serializer and a Postgres database in conjunction with a popular package, dj-stripe. Dj-stripe is saving some json data in a textfield (column=billing_details
) in the database, and it looks like so, with double quotes:
{"address":{"city":null,"country":null,"line1":null,"line2":null,"postal_code":"11111","state":null},"email":null,"name":"Jenny Rosen","phone":null}
Unfortunately, it seems that something (django? python?) is converting it to single quotes, (and adding some spaces after colons) as so:
{'address': {'city': None, 'country': None, 'line1': None, 'line2': None, 'postal_code': '11111', 'state': None}
My view is very basic:
class GetCustomerView(generics.ListAPIView):
authentication_classes = (TokenAuthentication,)
PaymentMethodSerializer
def list(self, request):
customer = Customer.objects.get(subscriber=request.user.organization_id)
cards = PaymentMethod.objects.filter(customer=customer.djstripe_id)
serializer = PaymentMethodSerializer(cards, many=True)
pprint(serializer.data)
if cards:
return Response(serializer.data)
else:
return Response('error', status=status.HTTP_400_BAD_REQUEST)`
and my serializer is basic too:
class PaymentMethodSerializer(serializers.ModelSerializer):
card = json.loads(serializers.JSONField())
billing_details = json.loads(serializers.JSONField())
class Meta:
model = PaymentMethod
fields = ( 'id', 'billing_details', 'card',)
Obviously it would probably be best stored in a JSONB field, but changing the package is not an option. That said, how do I go about preventing this conversion?
Upvotes: 3
Views: 2213
Reputation: 2000
The solution for me was to set the serializer to a DictField
class PaymentMethodSerializer(serializers.ModelSerializer):
card = serializers.DictField()
billing_details = serializers.DictField()
class Meta:
model = PaymentMethod
fields = ( 'id', 'billing_details', 'card',)
This caused the single quotes to come out as double quotes. Although this is a dict and isn't JSON (it takes a little more massaging to get to true json) this is a lot more friendly that having single quotes which are hard to replace. I don't exactly understand why a JSONfield doesn't serialize output to json by default, but maybe I have a lack of understanding.
Upvotes: 1