欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Django models的诡异异常RelatedObjectDoesNotExist

程序员文章站 2023-12-24 13:21:45
...

models代码如下:

class Course(models.Model):
    name = models.CharField(unique=True, max_length=64)
    price = models.PositiveIntegerField(default=19800)
    outline = models.TextField()

    def __str__(self):
            return "%s" % self.name

    class Meta:
        verbose_name_plural = "课程信息表"
        verbose_name = "课程信息表"


class ClassList(models.Model):
    course = models.ForeignKey("Course")
    semester = models.PositiveIntegerField(verbose_name="学期")
    class_type_choice = ((0, '脱产'),
                  (1, '周末'),
                  (2, '网络'),
                  )
    branch = models.ForeignKey("Branch")
    class_type = models.PositiveIntegerField(choices=class_type_choice)
    teachers = models.ManyToManyField("UserProfile")
    start_date = models.DateField()
    end_date = models.DateField()

    def __str__(self):
            return "%s(%s)" % (self.course, self.semester)

    class Meta:
        verbose_name_plural = "班级信息表"
        verbose_name = "班级信息表"
        unique_together = ("course", "semester")

两个表关系如上,ClassList表的course是一个外键,关联上面的Course表。

我想在ClassList中定义__str__函数,就像代码中写的。

我是用django的modelform来处理数据并构建web页面。

结果在进入那个由modelform构建的页面时,发生了异常

Django models的诡异异常RelatedObjectDoesNotExist

Django models的诡异异常RelatedObjectDoesNotExist

 

 

 C:\Users\Administrator\AppData\Roaming\Python\Python35\site-packages\django\db\models\fields\related_descriptors.py 下的line 193
        if rel_obj is None and not self.field.null:
            raise self.RelatedObjectDoesNotExist(
                "%s has no %s." % (self.field.model.__name__, self.field.name)
            )
        else:
            return rel_obj

so,就是那个RelatedObjectDoesNotExist,google了很久,发现有个网友说的很好:

https://*.com/questions/26270042/how-do-you-catch-this-exception#comment41357708_26270785

 

那个票最多的答案。
Django models的诡异异常RelatedObjectDoesNotExist

 

 正如他所说的Django is amazing when its not terrifying.我此时的内心是崩溃的。。。
代码更改如下:
class ClassList(models.Model):
    course = models.ForeignKey("Course")
    semester = models.PositiveIntegerField(verbose_name="学期")
    class_type_choice = ((0, '脱产'),
                  (1, '周末'),
                  (2, '网络'),
                  )
    branch = models.ForeignKey("Branch")
    class_type = models.PositiveIntegerField(choices=class_type_choice)
    teachers = models.ManyToManyField("UserProfile")
    start_date = models.DateField()
    end_date = models.DateField()

    def __str__(self):
        try:
            return "%s(%s)" % (self.course, self.semester)
        except Course.DoesNotExist:
            return "%s" % self.semester

 

正如大神网友所说,我抓住了这个异常,随便返回个不是外键的值就好了。

无FUCK说~~~希望能帮到大家。。。

 

上一篇:

下一篇: