Django Rest Framework-显示用户个人资料

时间:2019-04-30 04:18:31

标签: python django django-rest-framework

我的 users / models.py 文件如下所示。

class User(AbstractUser):
    is_customer = models.BooleanField(default=False)
    is_courier = models.BooleanField(default=False)
    is_merchant = models.BooleanField(default=False)


class Profile(models.Model):
    contact_number = models.CharField(max_length=10, unique=True)
    rating = models.IntegerField(blank=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    user = models.ForeignKey(User, on_delete=models.CASCADE)

我当前的 users / serializers.py 如下所示。

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

我的 users / api.py 如下所示。

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_class = UserSerializer

我的 users / urls.py 具有以下内容:

router.register('api/users', UserViewSet, 'users')

我当前的设置与UserViewSet一起使用时效果很好。 http://127.0.0.1:8000/api/users/根据ID显示所有用户,http://127.0.0.1:8000/api/users/1/显示用户。

我的问题是,当我转到下面的URL http://127.0.0.1:8000/api/users/1/profile时如何加载用户个人资料

非常感谢您的帮助。预先谢谢你。

2 个答案:

答案 0 :(得分:1)

Profile 模型创建新的序列化器

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = "__all__"

然后为 Profile 创建一个新的视图类。

from rest_framework.views import APIView
from rest_framework.response import Response
from django.shortcuts import get_object_or_404


class ProfileAPI(APIView):
    def get(self, request, *args, **kwargs):
        user = get_object_or_404(User, pk=kwargs['user_id'])
        profile_serializer = ProfileSerializer(user.profile)
        return Response(profile_serializer.data)

然后,在 urls.py

中连接视图
urlpatterns = [
    # your other url configs
    path('api/users/<user_id>/profile/', ProfileAPI.as_view())
]

Update-1

使用 ViewSet 类的实现

from rest_framework import viewsets
from rest_framework.response import Response
from django.shortcuts import get_object_or_404


class ProfileAPI(viewsets.ViewSet):
    def get(self, request, *args, **kwargs):
        user = get_object_or_404(User, pk=kwargs['user_id'])
        profile_serializer = ProfileSerializer(user.profile)
        return Response(profile_serializer.data)

Update-2

from rest_framework import viewsets


class ProfileAPI(viewsets.ModelViewSet):
    serializer_class = ProfileSerializer

    def get_queryset(self):
        return Profile.objects.filter(user=self.kwargs['user_id'])

并在您的urls.py中将视图集注册为

router.register('api/users/(?P<user_id>\d+)/profile', ProfileAPI, base_name='profile_api')

答案 1 :(得分:0)

我使用了** AbstractUser **和** custom user manager ** 我已经使用了ViewSets.ViewSet和Model Serializers

#urls.py文件#

l1 = ['x', 'y']
l2 = [1, 2]
d = {key: value for key, value in zip(l1, l2)}
print(d)  # {'x': 1, 'y': 2}

#views.py文件#

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ProfileViewSet, LoginViewSet, RegisterViewSet

router = DefaultRouter()
router.register(r'register', RegisterViewSet, basename='register')
router.register(r'login', LoginViewSet, basename='login')
router.register(r'profile', ProfileViewSet, basename='profile')

urlpatterns = [
path('', include(router.urls)),
]

#serializer.py文件#

from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
from .models import user_reg
from .serializers import RegisterSerializer


class ProfileViewSet(ViewSet):

    def partial_update(self, request, pk=None):    #partially update the profile

        try:
            user_detail = user_reg.objects.get(pk=pk)
           
            serializer = RegisterSerializer(user_detail,data=request.data, partial=True)

            if not serializer.is_valid():
                return Response({'data':'internal server error','message':'error aa gyi'},500)

            serializer.save()

        except Exception as e:

            return Response('some exception occured' + str(e))

        return Response('record Updated successfully')

    def retrieve(self,request, pk=None):    #get or retrieve the profile from database

        queryset = user_reg.objects.get(pk=pk)
    
        serializer_class = RegisterSerializer(queryset)
    
        return Response(serializer_class.data)

#models.py#

from rest_framework import serializers
from .models import user_reg

class RegisterSerializer(serializers.ModelSerializer):

    class Meta:
        model = user_reg
        fields = ('username','first_name','last_name','email')  #custom fields i made 
                                                                 u can change this