在ModelSerializer中使用外键的空白Imagefield

时间:2016-02-07 23:30:16

标签: python django django-models django-rest-framework

我有两个模型:userscomments

class GRUser(AbstractUser):
    class Meta:
        db_table = 'gruser'

    def avatar_big_path(self, filename):
        ext = filename.split('.')[-1]
        return 'images/user_avatars/big/{0}.{1}'.format(uuid.uuid4(), ext)

    def avatar_small_path(self, filename):
        ext = filename.split('.')[-1]
        return 'images/user_avatars/small/{0}.{1}'.format(uuid.uuid4(), ext)

    facebook_link = models.URLField(max_length=100, null=True, blank=True)
    about = models.CharField(max_length=160, blank=True)
    avatar_big = models.ImageField(upload_to=avatar_big_path, null=True, blank=True)
    avatar_small = models.ImageField(upload_to=avatar_small_path, null=True, blank=True)


class VideoComment(models.Model):

    class Meta:
        db_table = 'video_comment'
    video_comment_pk = models.AutoField(primary_key=True)
    parent_comment_fk = models.ForeignKey('self', null=True, blank=True, related_name='child_comments',
                                          db_column='parent_comment_fk')
    video_fk = models.ForeignKey(Video, related_name='video_comments', db_column='video_fk')
    user_fk = models.ForeignKey(GRUser, related_name='video_comments', db_column='user_fk')
    video_comment_dttm = models.DateTimeField(auto_now_add=True)
    text = models.CharField(max_length=1000)

和他们的ModelSerializers:

class UserListSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.GRUser
        fields = ('id',
                  'username',
                  'email',
                  'avatar_big',
                  'avatar_small',
                  )    

class VideoCommentListRetrieveSerializer(serializers.ModelSerializer):
    username = serializers.ReadOnlyField(source='user_fk.username')
    avatar_small = serializers.ReadOnlyField(source='user_fk.avatar_small')

    class Meta:
        model = models.VideoComment
        fields = ('video_comment_pk',
                  'parent_comment_fk',
                  'video_fk',
                  'user_fk',
                  'username',
                  'avatar_small',
                  'video_comment_dttm',
                  'text',
                  )

有些用户的空白avatar_small属性。在用户列表中,它们显示为

    {
        "id": 2,
        "username": "admin",
        "email": "admin@gmail.com",
        "avatar_big": null,
        "avatar_small": null
    },  

但是,在评论列表中,相同的用户会引发错误:

The `avatar_small` attribute has no file associated with it.

我使用SerializerMethodField

解决了这个问题
avatar_small = serializers.SerializerMethodField()

def get_avatar_small(self, obj):
    if obj.user_fk.avatar_small:
        return obj.user_fk.avatar_small.url
    else:
        return None

有没有更方便的方法来处理它? 为什么ModelSerializer默认不显示null

0 个答案:

没有答案