【发布时间】:2017-10-07 03:06:18
【问题描述】:
我试图作为特定于用户的单个对象(不是查询集)返回,而无需在请求的 URL 中指定标识符/pk。每个用户都有一个组织 FK。
即http://website/organisation 而不是 http://website/organisation/1
我收到以下错误,因为它需要此标识符:
AssertionError: Expected view OrganisationDetail to be called with a URL keyword argument named "user__organisation_id". Fix your URL conf, or set the.lookup_fieldattribute on the view correctly.
在使用 RetrieveModelMixin/GenericAPIView 时我需要如何/需要指定什么,以便它返回由 FK 链接的单个对象?
我的视图类:
class OrganisationDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin,generics.GenericAPIView):
serializer_class = OrganisationDetailSerializer
lookup_field = 'pk' #yes, I know this is the default and there's no need to speciy
def get_queryset(self):
return Organisation.objects.filter(pk=self.request.user.organisation_id)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
相关网址:
url(r'^api/v1/organisation/$', OrganisationDetail.as_view()),
我的模特:
class Person(AbstractUser):
organisation = models.ForeignKey(Organisation, related_name='members', null=True)
is_admin = models.BooleanField(default=False)
def __str__(self):
return self.first_name + " " + self.last_name + " - " + self.email
【问题讨论】:
标签: python django django-rest-framework