【发布时间】:2021-09-26 13:13:54
【问题描述】:
我正在使用 react 和 django_rest_framework 创建一个笔记保存应用程序。
我的笔记模型 -
from django.db import models
from django.contrib.auth.models import User
class Note(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.title
Note 序列化器 -
from rest_framework import serializers
from .models import Note
class NoteSerializer(serializers.ModelSerializer):
class Meta:
model = Note
fields = ("id", "title", "content")
为了注册和登录,我在这里关注答案 - Answer
我用来存储笔记的反应代码 -
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: this.state.title, content: this.state.note })
};
await fetch('http://localhost:8000/notes/', requestOptions);
现在,我如何将我的笔记对象连接到特定的登录用户,以便特定的笔记只对该用户可见?
这可以在 django 中使用 ForeignKey 来完成,但是如何在 django_rest_framework 中完成呢?
编辑 1
我遵循了@Abhyudai 给出的答案,但我收到了这个错误 -
django.db.utils.IntegrityError: NOT NULL constraint failed: notes_note.user_id
编辑 2
views.py -
from .serializers import NoteSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Note
from rest_framework import status
class NoteView(APIView):
def get(self, request, format=None):
notes = Note.objects.all()
serializer = NoteSerializer(notes, many=True)
return Response(serializer.data)
请帮忙。谢谢!
【问题讨论】:
-
你能不能显示
NoteSerializerviews.py。 -
@AliAref 添加了views.py
标签: javascript python reactjs django django-rest-framework