我需要通过Django Rest API创建User
个实例。需要扩展普通的Django内置User
,最常见的是UserProfile
模型。因此,必须使用API中User
和User
的单独表格来表示UserProfile
个对象。
我假设我可以制作一个基于函数的单一视图,它结合了来自User
和UserProfile
序列化器的序列化数据,但我真的很想知道它是否可以用同样的方法做同样的事情。基于类的视图。它需要有两个查询集和serializer_classes,甚至可能吗?
答案 0 :(得分:1)
您可以使用简单的APIView
来实现此目的:
from rest_framework.views import APIView
class GetProfileEmployeeView(APIView):
def get(self, request, format=None):
# I associate Django users to a matching Employee record via e-mail address
emp_profile = Employee.objects.get(email=self.request.user.email)
serializer = EmployeeSerializer(emp_profile)
return Response(serializer.data)
然后,在urls.py
中添加指向此视图的端点:
urlpatterns = [
url(r'^profile/?$', utility_views.GetProfileEmployeeView.as_view()),
]
当用户GET
该端点时,他们将返回其整个用户个人资料。你也可以疯狂地手动制作一个由来自多个模型对象的数据组成的响应:
def get(self, request, format=None):
employee = Employee.objects.get(id=self.request.employee.id)
company = toolbox.get_employee_company(employee)
profile_co = CompanySerializer(company).data
profile_co['licenses'] = AccountSerializer(Account.objects.get(company=company)).data['license_count']
profile = {}
profile['id'] = employee.id
profile['first_name'] = employee.first_name
profile['last_name'] = employee.last_name
profile['email'] = employee.email
profile['is_admin'] = employee.is_admin
profile['company'] = profile_co
return Response(profile)