python - 使用 Django Rest Framework 从方法序列化数据

标签 python django rest methods django-rest-framework

我无法理解 Django Rest Framework 在序列化数据时如何处理相关模型实例。

例如,我有两个模型都与 django `User' 相关:

from django.contrib.auth.models import User
from django.db import models

class UserStatus(models.Model):
    user = models.ForeignKey(User)
    created = CreationDateTimeField()

    def is_anonymous(self):
        return self.user.userprofile.anonymous_user


class UserProfile(models.Model):
    user = models.OneToOneField(User)
    anonymous_user = models.BooleanField(default=False)

如果我使用以下方法序列化模型实例,它工作正常:

from rest_framework import serializers

class UserStatusSerializer(serializers.ModelSerializer):
    get_anonymous = serializers.SerializerMethodField('get_anonymous_state')

    def get_anonymous_state(self, obj):
        return self.object.user.userprofile.anonymous_user

    class Meta:
        model = UserStatus
        fields = ('id', 'get_anonymous',)

我调用序列化程序的 View 结构如下:

def put(self, request, *args, **kwargs):
        user = self.request.user
        serializer = UserStatusSerializer(self.model.objects.filter(user=user, data=request.DATA)

        if serializer.is_valid():
                new_serializer = UserStatusSerializer(user)
                return Response(new_serializer.data, status=status.HTTP_200_OK)

如果我尝试使用模型 UserStatus 上存在的方法,我会收到错误消息:

class UserStatusSerializer(serializers.ModelSerializer):
    is_anonymous = serializers.Field(source='is_anonymous')

    class Meta:
        model = UserStatus
        fields = ('id', 'is_anonymous',)

在第二种方法中,我收到错误消息:

Exception Value: UserStatus has no user

我真的不明白这是怎么回事。如果我设置跟踪并逐行通过 PUT 请求,它工作正常并且存在正确的关系(例如,我在方法中,我可以访问 self.user。 userprofile.anonymous_user);它两次执行序列化,第二次中断。当我让我将它作为一个完整的代码块进行测试时,它也不起作用。对我做错了什么有什么建议吗?

最佳答案

你试过吗

is_anonymous = serializers.Field(source='user.userprofile.is_anonymous')

不调用方法?

关于python - 使用 Django Rest Framework 从方法序列化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22800561/

相关文章:

python - 如何覆盖 modelform 类的 save() 方法并添加缺失信息?

django - 扩展django组和权限

javascript - 向 Backbone 模型添加功能?

python - Pandas 将 float append 到 for 循环中的列

python - 无法在 Django 中加载模板 - 'TemplateDoesNotExist at/home/' 错误

python - 如何将列表中的字典转换为Python中的DataFrame?

python - shopify.RecurringApplicationCharge.cancel() AttributeError : 'function' object has no attribute 'body'

python - 在Python中,如何仅使用datetime包获取本地化时间戳?

java - Spring Integration 文件处理将其发送到 http

Android:将 URL 解析为没有空格字符的 Web 服务