django rest PrimaryKeyRelatedField(allow_empty = False,many = True,queryset = App.objects.all())不是JSON serializabl

时间:2016-11-01 08:30:09

标签: python django serialization django-rest-framework

我有一些嵌套的序列化程序,我将通过http请求以JSON格式获取用户对象,使用以下代码段:

import requests

r = requests.get('http://127.0.0.1:8000/accounts/users',
                 auth=("admin", "mat"))

但这是它的回报:

PrimaryKeyRelatedField(allow_empty=False, many=True, queryset=App.objects.all()) is not JSON serializabl

我尝试过很多方法,包括使用to_representation方法并继承自serializers.RelatedField。但总是得到相同的结果。

似乎我做错了什么。如果您对此有任何建议,我将不胜感激?

以下是序列化程序:

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('name',
                  'popularity')


class CategorySerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True)

    class Meta:
        model = Category
        fields = ('en_name',
                  'fa_name',
                  'tags')


class CpSerializer(serializers.ModelSerializer):
    class Meta:
        model = CP
        fields = ('en_name',
                  'fa_name',
                  'id_number')


class AppSerializer(serializers.ModelSerializer):
    category = CategorySerializer()
    cp = CpSerializer()

    class Meta:
        model = App
        fields = ('en_name',
                  'fa_name',
                  'package_name',
                  'build_number',
                  'downloads',
                  'cp',
                  'category')


class UserAppSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserApps
        app =  AppSerializer() # or even serializers.StringRelatedField()
        fields = ('status', 'user_rate', 'comment', 'app')

    def to_representation(self, instance):
        return None


class UserSerializer(serializers.HyperlinkedModelSerializer):

    id_number = serializers.CharField(read_only=True, source='userprofile.id_number')
    apps = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('username',
                  'password',
                  'first_name',
                  'last_name',
                  'email',
                  'id_number',
                  'apps')

    def get_apps(self, obj):
        if obj.username != "admin":
            return
        else:
            apps = UserAppSerializer(read_only=True,
                                     many=True)
            return apps


class UserProfileSerializer(serializers.HyperlinkedModelSerializer):

    user = UserSerializer()

    class Meta:
        model = UserProfile
        fields = ('user', 'id_number')

以下是我的观点的get方法:

def get(self, request):
    print("call get method on {}".format(self.__class__.__name__))
    if request.user.username == 'admin':
        users = User.objects.all()
        lookup_field = 'username'
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)

我已将apps中的UserProfile字段定义如下:

apps = models.ManyToManyField('UserApps')

UserApps app如下:

app = models.ManyToManyField(Application)

Application cpcategory中:

cp = models.ForeignKey('cp.CP')
category = models.ForeignKey(Category)

category中,tags已被定义为:

tags = models.ManyToManyField('Tag')

1 个答案:

答案 0 :(得分:1)

def get_apps(self, obj):
    if obj.username != "admin":
        return
    else:
        apps = UserAppSerializer(read_only=True,
                                 many=True)
        return apps

此功能不正确。 该函数将用户实例作为参数obj获取,并且应该返回app字段的值。 但是,该函数不对用户实例执行任何操作,而是返回值返回UserAppSerializer的空实例。

app = models.ManyToManyField(Application) 为清楚起见,这应该被称为apps apps = models.ManyToManyField(Application)

然后你的序列化器函数可以像这样重写

def get_apps(self, obj):
    if obj.username != "admin":
        return
    else:
        return UserAppSerializer(instance=obj.apps, 
                                 read_only=True, many=True).data