Django rest框架扩展了用户配置文件

时间:2016-04-08 08:43:52

标签: django rest python-3.x django-rest-framework

我最近发现了DRF,我失去了观看量,视图集和其他可能性。

我有一个带有扩展用户配置文件的Python3 / Django 1.8应用程序:

from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _


class Profile(models.Model):
    GENDER = (
        ('male', _('MALE')),
        ('female', _('FEMALE')),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.CharField(default='', max_length=500, null=True, blank=True)
    gender = models.CharField(max_length=10, choices=GENDER, null=True, blank=True)
    city = models.CharField(default='', max_length=30, null=True, blank=True)
    country = models.CharField(default='', max_length=30, null=True, blank=True)

我想允许与oauth2 / token Bearer连接的外部移动应用程序通过api获取当前连接用户的配置文件,并使用 编辑它路线:

GET或PUT / api / profile GET或PUT / api / user

我的第一个目的是只使用一条路线来操纵两个模型(通过/ api / profile),但是我失败了,我不确定将两个模型混合在一条路线后是否是一个好习惯。 / p>

我尝试了很多东西。我的最后一次尝试是获得这样的个人资料:

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'password', 'email', 'groups')

    password = serializers.CharField(write_only=True)


class UserViewSet(viewsets.ModelViewSet):
    @list_route(methods=['get', 'post'], permission_classes=[permissions.IsAuthenticated])
    def profile(self, request):
        u = User.objects.filter(pk=request.user.pk)[0]
        p = Profile.objects.filter(user=u)[0]
        return Response({"id": u.id, "first_name": u.first_name, "last_name": u.last_name, "email": u.email,
                     "city": p.city, "country": p.country, "bio": p.bio})

    permission_classes = [permissions.IsAuthenticated]
    queryset = User.objects.all()
    serializer_class = UserSerializer


router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

问题是:我未能尝试为PUT请求实现相同的功能。此外,我想在API方面做安全和防御性编码部分,在这种情况下,我甚至不使用序列化器。

你们能帮助我找到合适的人选吗?你有什么提示和建议吗?

干杯

1 个答案:

答案 0 :(得分:4)

我认为这就是你想要的:

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ('bio', 'gender', 'city', 'country')


class UserSerializer(serializers.ModelSerializer):

    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = ('url', 'username', 'password', 'email', 'groups', 'profile')

或者如果你想要它平坦:

class UserSerializer(serializers.ModelSerializer):

    bio = serializers.CharField(source='profile.bio')
    gender = serializers.CharField(source='profile.gender')
    #same for the others

    class Meta:
        model = User
        fields = ('url', 'username', 'password', 'email', 'groups', 'bio', 'gender')

我没有测试它,但应该接近你想要的,或者至少接近它。