How to POST and update using Django

2019-03-05 12:10发布

I have these two models:

class Lecture(models.Model):
    lecture_no = models.IntegerField(null=True)
    title = models.CharField(max_length=128, unique=True, null=True)
    youtubeLink = models.CharField(max_length=128, unique=True, null=True)
    course = models.ForeignKey(Course, null=True)
    keywords = models.TextField(max_length=300, null=True)
    #Could add Next Rerun Date & Time

    def __str__(self):
        return self.title

class Notes(models.Model):
    notes = models.TextField(null=True)
    lecture = models.ForeignKey(Lecture, null=True)

    def __str__(self):
        return str(self.notes)

I am trying to make it so that I can create new notes and update existing notes for specific lectures from within the Lecture page.

I have these views:

class LectureViewSet(viewsets.ModelViewSet):
    serializer_class = LectureSerializer

    # Queries the data to find the right lectures for a given course

    def get_queryset(self):
        course_id = self.request.query_params.get('course', False)
        if course_id:
            lectures = Lecture.objects.filter(course=course_id)
        else:
            lectures = Lecture.objects.all()
        return lectures

    @detail_route(methods=['post'])
    def set_notes(self, request, pk=None):
        lecture = self.get_object()
        serializer = NotesSerializer(data=request.data)
        if serializer.is_valid():
            lecture.set_notes(serializer.data['notes'])
            lecture.save()
            return Response({'status': 'notes saved'})
        else:
            return Response(serializer.errors,
                            status="Error.")

class NotesViewSet(viewsets.ModelViewSet):
    queryset = Notes.objects.all()
    serializer_class = NotesSerializer

    def get_queryset(self):
        lecture_id = self.request.query_params.get('lecture', False)
        if lecture_id:
            notes = Notes.objects.filter(lecture=lecture_id)
        else:
            notes = Notes.objects.all()
        return notes

Which I am using to try and allow for new notes to be posted, however, they seem to respond constantly with error:

lecture: {title: ["Lecture with this title already exists"] }

Which leads me to believe that it is trying to post new Notes instead of updating the existing one. I am also confused as to why it is producing this error instead of simply adding another Notes object to the database because if Lecture is a ForeignKey of Notes then doesn't that imply many-to-one relationship?

EDIT: I've updated my serializers to include create and update methods:

def create(self, validated_data):
    notes = Notes.objects.create(**validated_data)
    return notes

def update(self, instance, validated_data):
    instance.notes = validated_data.get('notes', instance.notes)
    return instance

But I still receive this error:

Cannot assign "OrderedDict([('lecture_no', 1), ('title',"Lecture Title, ('youtubeLink', 'Link1'), ('course', ), ('keywords', 'These keywords.')])": "Notes.lecture" must be a "Lecture" instance.

0条回答
登录 后发表回答