【问题标题】:Is there a way to get JSON data without tying to model in django restframework?有没有办法在不尝试在 django rest 框架中建模的情况下获取 JSON 数据?
【发布时间】:2015-05-23 10:59:36
【问题描述】:

我想在我的后端获取 JSON 数据而不将其绑定到模型。例如,在这样的 json 数据中,我想访问quantity,但不希望它与任何模型相关联。

{
  "email": "some@gmail.com"
  "quantity": 5,
  "profile": {
      "telephone_number": "333333333"
  }
}

我的序列化器:

class PaymentSerializer (serializers.ModelSerializer):
    profile = UserProfilePaymentSerializer()
    # subscription = UserSubscriptionSerializer()

    class Meta:
        model = User
        fields = ('email', 'profile',)

    def create(self, validated_data):
        profile_data = validated_data.pop('profile')
        user = AuthUser.objects.create(**validated_data)
        Profile.objects.create(user=user, **profile_data)
        return user

    def update (self, instance, validated_data):
        instance.quantity = validated_data.get('quantity', instance.quantity)
        print instance.quantity
        return instance

当我发送 PATCH 请求时,我收到一个错误

“用户”对象没有“数量”属性

【问题讨论】:

  • 我认为Meta中定义的模型类应该是AuthUser而不是User
  • 但这仍然不能解决 quantity 在 JSON 中传递但不存在于模型中的问题。

标签: python django django-rest-framework


【解决方案1】:

你可以使用json

import json
json.loads('{ "email": "some@gmail.com","quantity": 5,"profile": {"telephone_number": "333333333"}}')[u'quantity']

我认为你也可以使用简单的 json(未测试):

from urllib import urlopen
import simplejson as json

url = urlopen('yourURL').read()
url = json.loads(url)

print url.get('quantity')

【讨论】:

    【解决方案2】:

    AFAIK,将额外数据传递给ModelSerializer 并且模型中缺少的属性将按照您的说明抛出。如果您想拥有模型中不存在的额外属性,restore_object 需要覆盖。

    GitHub Issue 和类似SO Answer 的几个例子

    【讨论】:

      【解决方案3】:

      你可以试试这样的:

      class PaymentSerializer (serializers.ModelSerializer):
          ...
      
          quantity = serializers.SerializerMethodField('get_quantity')
      
          class Meta:
              model = User
              fields = ('email', 'profile', 'quantity',)
      
          def get_quantity(self, user):
              return len(user.email)
      
          ...
      

      基本上,您修改Meta,而不是实际模型,以在输出中添加一个额外的quantity 字段。您将此字段定义为SerializerMethodField。序列化程序将调用方法get_quantity 来获取字段的值。在示例中,返回的数量等于用户的email 地址的长度。这通常对计算域很有用。这些派生字段自动为只读,在PUTPOST 上将被忽略。

      参考是here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-11
        • 2014-02-26
        • 1970-01-01
        • 2016-12-10
        • 1970-01-01
        • 2019-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多