说,我有一个模型Post
与User
的内置liked_post
有很多关系
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
like = models.ManyToManyField(User, related_name='liked_posts')
逻辑上一切都很好,我可以很好地添加/删除喜欢的关系。
但是,当我为save
引入附加属性saved_post
时,就像这样:
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
like = models.ManyToManyField(User, related_name='liked_posts')
save = models.ManyToManyField(User, related_name='saved_posts')
在尝试实例化Post
模型时,它总是在下面抛出错误。
ValueError: "<Post: Post object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used.
请注意,我什至没有修改/添加任何自定义save()
方法。
即使我尝试致电p = Post.object.create()
,错误也会突然出现。
据我所知,我需要先保存Post
,然后再添加任何like
或save
关系。但是即使保存Post实例,我也出错了。
====
编辑1
包括完整的堆栈跟踪:
Error
Traceback (most recent call last):
File "/home/rahmat/Upworks/06_Made_Gatewee/gatewee/app_post/tests/test_post_save.py", line 34, in setUp
p = Post.objects.create()
File "/home/rahmat/Upworks/06_Made_Gatewee/gatewee/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/rahmat/Upworks/06_Made_Gatewee/gatewee/venv/lib/python3.6/site-packages/django/db/models/query.py", line 422, in create
obj.save(force_insert=True, using=self.db)
File "/home/rahmat/Upworks/06_Made_Gatewee/gatewee/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 527, in __get__
return self.related_manager_cls(instance)
File "/home/rahmat/Upworks/06_Made_Gatewee/gatewee/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 840, in __init__
(instance, self.pk_field_names[self.source_field_name]))
ValueError: "<Post: Post object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used.
答案 0 :(得分:1)
这里的问题是save
模型中的Post
字段与内部save
方法冲突并导致此错误。
只需更改字段名称,例如:
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
like = models.ManyToManyField(User, related_name='liked_posts')
saved_posts = models.ManyToManyField(User, related_name='saved_posts')