django /api/course/中的完整性错误(1048,“列'类别标识'不能为空”)

voase2hg  于 2022-12-05  发布在  Go
关注(0)|答案(2)|浏览(246)

大家好,我需要一些帮助来解决Django中的这个问题 *IntegrityError at /api/course/(1048,“Column 'category_id' cannot be null”)我在尝试插入新课程时遇到了这个问题 *
课程(型号.型号):

category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE)
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE , related_name='teacher_courses')
title = models.CharField(max_length=150)
description = models.TextField()  
featured_img = models.ImageField(upload_to='course_imgs/',null=True)
techs = models.TextField(null=True)

class Meta:
    verbose_name_plural = "3. Courses"   

def related_content(self):
        related_content=Course.objects.filter(techs__icontains=self.techs)
        return serializers.serialize('json',related_content)     

def tech_list(self):
    tech_list = self.techs.split(',')
    return tech_list 

def __str__(self):
    return self.title

类课程列表(泛型.ListCreateAPIView):

queryset = models.Course.objects.all()
serializer_class = CourseSerializer 

def get_queryset(self):
    qs = super().get_queryset()
    if 'result' in self.request.GET:
        limit = int(self.request.GET['result'])
        qs = models.Course.objects.all().order_by('-id')[:limit]  
    
    if 'category' in self.request.GET:
        category = self.request.GET['category']
        qs = models.Course.objects.filter(techs__icontains=category)

    if 'skill_name' in self.request.GET and 'teacher' in self.request.GET:
        skill_name = self.request.GET['skill_name']   
        teacher = self.request.GET['teacher']   
        teacher = models.Teacher.objects.filter(id=teacher).first()
        qs = models.Course.objects.filter(techs__icontains=skill_name,teacher=teacher) 

    return qs

类CourseSerializer(序列化程序.模型序列化程序):

class Meta:
    model = models.Course
    fields =['id','title','description','category_id','teacher','featured_img','techs','course_chapters','related_content','tech_list']
    depth=1

我已经寻找了几个小时的解决方案,但我没有得到任何方法来解决这个问题,我希望你能帮助我,谢谢

afdcj2ne

afdcj2ne1#

完整性错误是数据库错误,您试图输入课程对象,但没有指定(在您的情况下)该课程对象连接到哪个CourseCategory对象。docs如下。您必须选择一个现有的CourseCategory来链接该课程。

jm2pwxwz

jm2pwxwz2#

问题出在Course模型中的category字段。

category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE)

您尚未将任何CourseCategory对象指派给您的字段。如果这是个错误,您应该指派一个CourseCategory。否则,如果您想要选择是否可以将CourseCategory接受为null,您应该将该行变更为:

category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE, blank=True, null=True)

此外,您需要将序列化程序中的category_id更改为category。如果序列化程序字段不是自定义的,则它们应该与各自模型的字段名称相匹配。

相关问题