我正在开发一个控制面板应用程序,用户可以在其中创建成员资格并登录到与这些成员资格相关的服务器(登录名不是django用户帐户,它们是一个独立的实体)。
我想限制django rest框架javascript api客户端基于将登录名链接到成员表的外键返回的登录名列表。
似乎我应该使用查询参数,但是我不确定如何将查询参数传递给javascript API。
这是我目前正在使用的javascript代码:
var auth = new coreapi.auth.SessionAuthentication({
csrfCookieName: 'csrftoken',
csrfHeaderName: 'X-CSRFToken'
})
var client = new coreapi.Client({auth: auth});
let action = ["login", "list"];
client.action(schema, action, params).then(function(result) {
console.log(result);
});
我如何告诉javascript API传递:member_id = 5到此请求?
在Django方面:
models.py(简体):
class Member(models.Model):
name = models.CharField(max_length=64)
disk_quota = models.PositiveIntegerField(default=50000000000)
class Login(models.Model):
member = models.ForeignKey(Member, on_delete=models.CASCADE)
username = models.CharField(max_length=254)
password = models.CharField(max_length=64, blank=True)
serializers.py:
class MemberSerializer(serializers.ModelSerializer):
class Meta:
model = Member
fields = '__all__'
class LoginSerializer(serializers.ModelSerializer):
class Meta:
model = Login
fields = '__all__'
urls.py
router = routers.DefaultRouter()
router.register(r'member', views.ApiMemberViewSet, base_name = 'Member')
router.register(r'login', views.ApiLoginViewSet, base_name = 'Login')
urlpatterns = [
path('api/docs/', include_docs_urls(title='Petal API service')),
path('api/schema/', get_schema_view(title='Pastebin API')),
path('api/', include(router.urls)),
}
views.py:
class ApiLoginViewSet(viewsets.ModelViewSet):
serializer_class = LoginSerializer
def get_queryset(self):
return Login.objects.filter(member=request.query_params['member_id'])
答案 0 :(得分:0)
答案似乎是使用DRF Nested Routers。
然后...
urls.py:
#from rest_framework import routers
from rest_framework_nested import routers
router = routers.DefaultRouter()
router.register(r'member', views.ApiMemberViewSet, base_name = 'Member')
login_router = routers.NestedSimpleRouter(router, r'member', lookup='member')
login_router.register(r'login', views.ApiLoginViewSet, base_name='Login')
urlpatterns = [
path('api/docs/', include_docs_urls(title='Petal API service')),
path('api/schema/', get_schema_view(title='Pastebin API')),
path('api/', include(router.urls)),
path('api/', include(login_router.urls)),
]
and views.py:
class ApiLoginViewSet(viewsets.ModelViewSet):
serializer_class = LoginSerializer
permission_classes = (PetalApiPermissions,)
def get_queryset(self):
return Login.objects.filter(member=self.kwargs['member_pk'])
最后是javascript:
// Build a client.
var auth = new coreapi.auth.SessionAuthentication({
csrfCookieName: 'csrftoken',
csrfHeaderName: 'X-CSRFToken'
})
var client = new coreapi.Client({auth: auth});
let action = ["member", "login", "list"];
let params = { member_pk: 4 };
client.action(schema, action, params).then(function(result) {
console.log(result);
});