gpt4 book ai didi

python - 值错误 : needs to have a value for field "" before this many-to-many relationship can be used

转载 作者:行者123 更新时间:2023-12-05 08:42:26 26 4
gpt4 key购买 nike

Django 版本:1.10.4异常类型:ValueError

Exception Value:    
"<SchoolBook: 0 test1 Test2 Test3 2011 122>" 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)

问题出在我试图保存对象时。

最佳答案

在实例保存之前,您不能访问多对多关系的相关对象!该实例必须具有中间 m2n 表的 id 以将其外键(通过 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)

关于python - 值错误 : needs to have a value for field "" before this many-to-many relationship can be used,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41781600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com