我有一个由 Django REST 框架创建的 API,它向我的 Vue.js 前端提供数据。在我尝试发布到 API 之前,一切都很好。我得到的错误是:
django.db.utils.IntegrityError: null value in column "ifflist_id" violates not-null constraint
DETAIL: Failing row contains (100, do more stuff, f, null).
这是我要发布到的模型:
class TodoItem(models.Model):
text = models.CharField(max_length=200) # this is the text of the actual to-do
ifflist = models.ForeignKey(IffList,
on_delete=models.CASCADE,
related_name='item')
is_completed = models.BooleanField(default=False)
这是 serializers.py:
class TodoItemSerializer(serializers.ModelSerializer):
class Meta:
model = TodoItem
fields = '__all__'
depth = 1
这是 API views.py:
class TodoListCreateAPIView(ListCreateAPIView):
queryset = TodoItem.objects.all() # this returns all the things, which is bad
permission_classes = (IsAuthenticated, )
serializer_class = TodoItemSerializer
lookup_field = 'id'
class TodoRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
queryset = TodoItem.objects.all() # this returns all the things, which is bad
permission_classes = (IsAuthenticated, )
serializer_class = TodoItemSerializer
lookup_field = 'id'
相关的urls.py:
path('api/', api_views.IffListCreateAPIView.as_view(), name='ifflist_rest_api'),
path('api/todoitems/', api_views.TodoListCreateAPIView.as_view(), name='todoitem_rest_api'),
path('api/user/', api_views.UserListCreateAPIView.as_view(), name='user_rest_api'),
# api/:slug
path('api/<int:id>/', api_views.IffListRetrieveUpdateDestroyAPIView.as_view(), name='ifflist_rest_api'),
path('api/todoitems/<int:id>/', api_views.TodoRetrieveUpdateDestroyAPIView.as_view(), name='todoitem_rest_api'),
最后,神奇的 Vue.js 方法:
addTodo: function () {
let new_todo_item = document.querySelector('#new_todo_item').value;
this.newTodo = {'text': new_todo_item, 'ifflist_id': this.displayedIfflist.id};
console.log(this.newTodo.text);
console.log(this.newTodo.ifflist_id);
let csrf_token = Cookies.get('csrftoken');
this.$http.post('/api/todoitems/', this.newTodo, {headers: {'X-CSRFToken': csrf_token}})
.then((response) => {
this.loading = false;
this.getIfflist(this.displayedIfflist.id);
})
.catch((err) => {
this.loading = false;
console.log(err);
})
},
我正在使用 Django 2 和 Vue 2。
最佳答案
原来这里是depth属性:
class TodoItemSerializer(serializers.ModelSerializer):
class Meta:
model = TodoItem
fields = '__all__'
depth = 1
一旦我删除它,一切都很好。这似乎是一个奇怪的 DRF 错误......
关于Django REST Framework 和 Vue.js 在发布时抛出 IntegrityError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49743753/