簡體   English   中英

有沒有一種方法可以獲取JSON數據而無需在Django restframework中建立模型?

[英]Is there a way to get JSON data without tying to model in django restframework?

我想在我的后端上獲取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請求時,出現錯誤

“用戶”對象沒有屬性“數量”

你可以使用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')

AFAIK,將額外的數據傳遞給ModelSerializer並在模型中缺少屬性將按照您的說明進行拋出。 如果要具有模型中不存在的額外屬性,則必須重寫restore_object

幾個例子GitHub Issue和類似的SO Answer

您可以嘗試這樣的事情:

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上將被忽略。

參考在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM