如何在django rest框架中获取JSON数据而不将其绑定到模型

时间:2015-03-20 02:27:55

标签: python django django-rest-framework

我将以下数据发送到我的django rest框架应用程序。

{
 "email": "sa@gmail.com"
  "profile": {
              stripe_token: "tok_15iFaJRbriArhT", 
              stripe_id: "cus_5u3iksCCw", 
              quantity: "5"
            },
  "subscription": {
              subscription_name: "noidea"
            }
}

根据我的序列化程序和模型,我可以获得除quantity之外的所有内容,因为我的任何模型上都没有称为数量的字段。但我只想抓住数量字段中发送的值,然后用它做一些事情。

这就是我到目前为止所做的事情:

serializers.py

class UserProfilePaymentSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('stripe_id', 'subscribed','stripe_token')

class UserSubscriptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Subscriptions
        fields = ('subscription_name',)

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

    class Meta:
        model = User
        fields = ('email', 'profile','subscription',)
    def update (self, instance, validated_data):
        profile_data = validated_data.pop('profile')
        subscription_data = validated_data.pop('subscription')
        print profile_data
        print subscription_data

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    telephone_number = models.CharField(max_length=100)
    stripe_id = models.CharField(max_length=255)
    subscribed = models.BooleanField(default=False)
    stripe_token = models.CharField(max_length=255)

class Subscriptions(models.Model):
    user = models.ManyToManyField(User)
    subscription_name = models.CharField(max_length=100)

1 个答案:

答案 0 :(得分:0)

quantity字段添加到UserProfilePaymentSerializer。然后,您可以在经过验证的数据字典中访问quantity field

class UserProfilePaymentSerializer(serializers.ModelSerializer):

    quantity = serializers.CharField()

    class Meta:
        model = UserProfile
        fields = ('stripe_id', 'subscribed','stripe_token')

class UserSubscriptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Subscriptions
        fields = ('subscription_name',)

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

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

    def update (self, instance, validated_data):
        ....
        quantity = validated_data['profile']['quantity']
        ....