尝试在Django - ForeignKey Relationship中获取字段值时获得AttributeError

时间:2017-10-28 06:47:12

标签: python django django-rest-framework

请使用序列化程序检查此错误。 我有一个模特阿凡达:

class Avatar(models.Model):
    user = models.ForeignKey(User, related_name='avatar_user', null=True)
    photoset = models.ForeignKey(PhotoSet, null=True, blank=True)
    primary = models.BooleanField(default=True)
    date_uploaded = models.DateTimeField(default=datetime.datetime.now)
    image = models.ImageField(max_length=1024, upload_to=avatar_file_path)

我创建了一个带头像的序列化程序用户

from django.contrib.auth.models import User

class BasicAvatarSerializer(ModelSerializer):
    class Meta:
        model = Avatar
        fields = [
            'user',
            'photoset',
            'image',
        ]

class UserBasicSerializer(ModelSerializer):
    avatar_set = BasicAvatarSerializer(many=True)
    class Meta:
        model = User
        fields = [
            'username',
            'avatar_set',
            'first_name',
            'last_name',
        ]

但它得到错误:

AttributeError at /api/v1/users/
Got AttributeError when attempting to get a value for field `avatar_set` on serializer `UserBasicSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `User` instance.
Original exception text was: 'User' object has no attribute 'avatar_set'.

view error by photo

1 个答案:

答案 0 :(得分:1)

我成功完全修复了它:

from django.contrib.auth.models import User

class BasicAvatarSerializer(ModelSerializer):
    class Meta:
        model = Avatar
        fields = [
            'user',
            'photoset',
            'image',
        ]

class UserBasicSerializer(ModelSerializer):
    avatar_user = BasicAvatarSerializer(many=True)
    class Meta:
        model = User
        fields = [
            'username',
            'avatar_user',
            'first_name',
            'last_name',
        ]

将avatar_set更改为avatar_user,因为用户中的 related_name ='avatar_user'。谢谢@PRMoureu和@rollinger!