当前位置:  开发笔记 > 编程语言 > 正文

ValueError:必须先使用字段“”的值,然后才能使用这种多对多关系

如何解决《ValueError:必须先使用字段“”的值,然后才能使用这种多对多关系》经验,为你挑选了1个好方法。

Django版本:1.10.4异常类型:ValueError

Exception Value:    
"" needs to have a value for field "schoolbook" before this many-to-many relationship can be used.

请帮助避免此错误:

class Subject(models.Model):
    name = models.CharField(max_length=256)
    slug = models.SlugField(max_length=256, blank=True)

def __str__(self):
    return self.name

def save(self, *args, **kwargs):
    if not self.id:
        self.slug = slugify(self.name, separator='_')
    return super(Subject, self).save(*args, **kwargs)

class SchoolBook(models.Model):
    parent_subject = models.ManyToManyField(Subject)
    year = models.SmallIntegerField()
    name = models.CharField(max_length=256,blank=True)
    autors = models.CharField(max_length=256)
    slug = models.SlugField(max_length=256, blank=True, unique=True)
    f_file = models.FileField(upload_to=directory_path)

def __str__(self):
    return '{0} {1} {2}'.format(
        self.name, self.autors, self.year)

def save(self, *args, **kwargs):
    if not self.id:
        subject_name = [self.parent_subject.values()[i]['name'] for i in range(len(self.parent_subject.values()))]
        self.name = ' '.join(subject_name)
        self.slug = slugify("{} {} {} {} {}".format(self.name, self.autors,self.year, self.pages, self.c_class))
    return super(SchoolBook, self).save(*args, **kwargs)

问题是当我尝试保存对象时。



1> schwobaseggl..:

保存实例之前,您无法访问多对多关系的相关对象!该实例必须具有一个id中间m2n表的,以将其外键(名称为schoolbook,因此显示错误消息)指向:

def save(self, *args, **kwargs):
    if not self.id:
        super(SchoolBook, self).save(*args, **kwargs)
    # process self.parent_subject (should be called ...subjects, semantically)
    super(SchoolBook, self).save(*args, **kwargs)

推荐阅读
ar_wen2402851455
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有