api_urls.py:
urlpatterns = [
url(r'^accounts/', include('apps.accs.urls')),
]
apps.accs.urls:
router = DefaultRouter()
router.register('', AccountViewSet, 'accounts')
urlpatterns += router.urls
models.py:
class Account(models.Model):
pass
class TargetUser(models.Model):
account = models.ForeignKey(Account, related_name='target_users')
views.py:
class AccountViewSet(viewsets.ModelViewSet):
serializer_class = AccountSerializer
queryset = Account.objects.all()
@detail_route(methods=['get', 'post'])
def target_users(self, request, pk=None):
account = self.get_object()
if request.method == 'POST':
# here I'm creating the instance of TargetUser
elif request.method == 'GET':
# here I'm getting the list of TargetUser instances
根据上面的代码,我有以下网址:
/accounts/
- 我在这里获得了帐户清单
/accounts/{pk}/
- 我在这里获得特定帐户
/accounts/{pk}/target_users/
- 如果GET
,我会获得属于特定帐户的TargetUser
个实例列表;如果POST
,我会为特定帐户创建新的TargetUser
实例
问题是 - 我应该如何实现以下网址 -
/accounts/{pk}/target_users/{user_pk}
有GET
和DELETE
特定目标用户的可能性。
非常感谢!!!