Django外键关联保存问题

我用的django版本为3.2.6,外键关联的对象已经保存了,并且在数据库中已经查询到数据了,但是在保存包含该外键的对象的时候还是报错"save() prohibited to prevent data loss due to unsaved related object",使用obj.objects.get的方式再次从数据库获取数据又可以,实在整不明白 class Grade(models.Model): id = models.IntegerField(primary_key=True) grade = models.CharField(max_length=50, unique=True)

class Stu(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50, unique=True) grade_of_stu = models.ForeignKey(Grade, to_field="grade", on_delete=models.CASCADE)

#####################################Django shell

In [17]: g = Grade(grade="3")

In [18]: g.save()

In [19]: stu = Stu(name="Fred", grade_of_stu=g)

In [20]: stu.save()

ValueError Traceback (most recent call last) <ipython-input-20-a0e3017ded06> in <module> ----> 1 stu.save()

C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\base.py in save(self, force_insert, force_update, using, update_fields) 680 non-SQL backends), respectively. Normally, they should not be set. 681 """ --> 682 self._prepare_related_fields_for_save(operation_name='save') 683 684 using = using or router.db_for_write(self.class, instance=self)

C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\base.py in _prepare_related_fields_for_save(self, operation_name) 930 if not field.remote_field.multiple: 931 field.remote_field.delete_cached_value(obj) --> 932 raise ValueError( 933 "%s() prohibited to prevent data loss due to unsaved " 934 "related object '%s'." % (operation_name, field.name)

ValueError: save() prohibited to prevent data loss due to unsaved related object 'grade_of_stu'.

In [21]: stu = Stu(name="Fred", grade_of_stu=Grade.objects.get(grade="3"))

In [22]: stu.save()

In [23]:

评论 0