我的API的設計是文章列表
{
"id": "667c476ca953483493afa265e5d500b0",
"name": "Home"
}
這是GET API的結果。在發佈中,我想要發佈設備列表。例如,如果用戶想要將設備發佈到主頁組,則我設計的網址是/ group/group_token/add(/ group/667c476ca953483493afa265e5d500b0/add)。數據發送格式爲
{
"devices":[<device_id1>, <device_id2>]
}
i.e
{
"devices":"[5ac41ba7e6ae4628982b2c81c99343a8], [7nu21ba7e6ae4628982b2c81c99343a8]"
}
這裏是我的模型,串行和APIView到目前爲止,我已經做了
class BaseDevice(PolymorphicModel):
name = models.CharField(max_length=250, blank=False, null=False)
owner = models.ForeignKey(User, blank=False, null=False)
token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
group = models.ForeignKey('DeviceGroup', related_name="groups", null=True, blank=True)
class Device(BaseDevice):
description = models.TextField(blank=True, null=True)
class DeviceGroup(models.Model):
token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
name = models.CharField(max_length=250, blank=False, null=False)
owner = models.ForeignKey(User, blank=False, null=False)
class DeviceGroupSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(source='token', format='hex', read_only=True)
class Meta:
model = DeviceGroup
fields = ['id','name']
class DevicesGroupsAPIView(APIView):
permission_classes = (permissions.IsAuthenticated,)
def get_serializer_class(self):
if self.request.user.is_staff:
return DeviceGroupSerializer
def get_object(self, user, token):
try:
return BaseDevice.objects.filter(owner=user).get(token=token)
except ObjectDoesNotExist:
return error.RequestedResourceNotFound().as_response()
def get(self, request, format=None):
reply = {}
try:
groups = DeviceGroup.objects.filter(owner=request.user)
reply['data'] = DeviceGroupSerializer(groups, many=True).data
except:
reply['data'] = []
return Response(reply, status.HTTP_200_OK)
def post(self, request, token=None, format=None):
device_group_instance = DeviceGroup.objects.get(token=token)
for device_token in request.data['devices']:
device = Device.objects.get(token=device_token, owner=request.user)
device.group = device_group_instance
device.save()
我該怎麼辦張貼?令牌部分出現錯誤。它說
DeviceGroup匹配查詢不存在。
我應該如何發佈?
UPDATE
弗里斯特截圖 URL是device_group /。當我嘗試從那裏發佈。我得到上面的錯誤不匹配查詢一個
第二個屏幕
的URL是在截圖瀏覽器。我沒有得到設備列表發佈,而是我看到名稱字段。
不知何故,你必須通過你的'後()'函數提供有效令牌(或從函數中檢索)。 –
抱歉,我不理解你。你能告訴我一個例子嗎? – milan