【问题标题】:Django automatically converting double quotes to single quotes in text fieldDjango自动将文本字段中的双引号转换为单引号
【发布时间】:2020-02-28 20:00:51
【问题描述】:

我有一个非常基本的 django 视图和序列化程序以及一个 Postgres 数据库以及一个流行的包 dj-stripe。 dj-stripe 正在将一些 json 数据保存在数据库中的文本字段(column=billing_details)中,看起来像这样,带双引号:

{"address":{"city":null,"country":null,"line1":null,"line2":null,"postal_code":"11111","state":null},"email":null,"name":"Jenny Rosen","phone":null}

不幸的是,似乎有些东西(django?python?)正在将其转换为单引号,(并在冒号后添加一些空格):

{'address': {'city': None, 'country': None, 'line1': None, 'line2': None, 'postal_code': '11111', 'state': None}

我的观点很基本:

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)`

我的序列化器也是基本的:

class PaymentMethodSerializer(serializers.ModelSerializer):
  card = json.loads(serializers.JSONField())
  billing_details = json.loads(serializers.JSONField())

  class Meta:
    model = PaymentMethod
    fields = ( 'id', 'billing_details', 'card',)

显然,它可能最好存储在 JSONB 字段中,但更改包不是一种选择。也就是说,我该如何阻止这种转换?

【问题讨论】:

  • JSON 字段将解析数据库中的内容 - 在您的情况下,它将被转换为您在打印时看到的字典。不过,这根本不应该是一个问题
  • @IainShelvington 谢谢...这只是一个问题,因为在 javascript 中使用 python dict 很痛苦。

标签: json django postgresql django-rest-framework


【解决方案1】:

我的解决方案是将序列化程序设置为 DictField

class PaymentMethodSerializer(serializers.ModelSerializer):
  card = serializers.DictField()
  billing_details = serializers.DictField()

  class Meta:
    model = PaymentMethod
    fields = ( 'id', 'billing_details', 'card',)

这导致单引号作为双引号出现。虽然这是一个 dict 并且不是 JSON(要获得真正的 json 需要更多的按摩),但这比使用难以替换的单引号要友好得多。我不完全明白为什么默认情况下 JSONfield 不将输出序列化为 json,但也许我缺乏理解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    相关资源
    最近更新 更多