是否可以在发布新对象的同时指定其id,而不是自动递增?这是一次导入,数据库id序列将在之后更正。在
class TestModelSerializer(serializers.ModelSerializer):
class Meta:
model = TestModel
fields = ('id', 'name')
class TestModelViewSet(viewsets.ModelViewSet):
queryset = TestModel.objects.all()
serializer_class = TestModelSerializer
import requests
def test_post(endpoint):
data = {
"id": 30,
"name": "Test",
}
r = requests.post(endpoint, data=data)
print(r.status_code, r.reason)
test_post('http://localhost:8000/api/test_model/30/')
>>> 405 Method Not Allowed
test_post('http://localhost:8000/api/test_model/')
>>> 201 Created
201 Created
创建一个新对象,但使用序列中的下一个id而不是所需的id
我也试过r = requests.put('http://localhost:8000/api/test_model/30/', data=data)
,但是得到了404 Not Found
这可以工作,但我不确定,我相信django rest从django模型中读取id是一个自动递增字段,因此不能使用提供的id创建。但如果您显式地将其指定为整数字段,则可以使用它。在
相关问题 更多 >
编程相关推荐