如何序列化模型中的方法?

时间:2017-03-19 10:33:28

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

如何在此模型中序列化get_picture(self)方法?我正在开发一个社交网络,我需要序列化这个方法,以获得用户个人资料图片的json网址,以便在Android应用程序中处理它。

class Profile(models.Model):
     user = models.OneToOneField(User)
     location = models.CharField(max_length=50, null=True, blank=True)
     url = models.CharField(max_length=50, null=True, blank=True)
     job_title = models.CharField(max_length=50, null=True, blank=True)

     class Meta:
         db_table = 'auth_profile'

     def __str__(self):
         return self.user.username

     def get_url(self):
         url = self.url
         if "http://" not in self.url and "https://" not in self.url and len(self.url) > 0:  # noqa: E501
            url = "http://" + str(self.url)

         return url

     def get_picture(self):
         no_picture = 'http://trybootcamp.vitorfs.com/static/img/user.png'
         try:
            filename = settings.MEDIA_ROOT + '/profile_pictures/' +\
                self.user.username + '.jpg'
            picture_url = settings.MEDIA_URL + 'profile_pictures/' +\
                self.user.username + '.jpg'
            if os.path.isfile(filename):
               return picture_url
            else:
                gravatar_url = 'http://www.gravatar.com/avatar/{0}?{1}'.format(
                hashlib.md5(self.user.email.lower()).hexdigest(),
                urllib.urlencode({'d': no_picture, 's': '256'})
                )
                return gravatar_url

          except Exception:
              return no_picture

2 个答案:

答案 0 :(得分:0)

使用SerializerMethodField

在序列化程序文件中。

# serializers.py

from rest_framework import serializers

class ProfileSerializer(serializers.ModelSerializer):
    get_picture = serializers.SerializerMethodField()

您的models.py原样

# models.py

class Profile(models.Model):
    ...

    class Meta:
        model = Profile

    def get_picture(self):
        no_picture = 'http://trybootcamp.vitorfs.com/static/img/user.png'
        try:
           filename = settings.MEDIA_ROOT + '/profile_pictures/' +\
               self.user.username + '.jpg'
           picture_url = settings.MEDIA_URL + 'profile_pictures/' +\
               self.user.username + '.jpg'
           if os.path.isfile(filename):
               return picture_url
           else:
               gravatar_url = 'http://www.gravatar.com/avatar/{0}?{1}'.format(
               hashlib.md5(self.user.email.lower()).hexdigest(),
           urllib.urlencode({'d': no_picture, 's': '256'})
           )
               return gravatar_url
        except Exception:
            return no_picture

答案 1 :(得分:0)

您可以使用source填充该字段。

serializers.URLField(source='get_picture', read_only=True)

http://www.django-rest-framework.org/api-guide/fields/#source