当前位置: 首页 > 知识库问答 >
问题:

禁止保存()以防止由于未保存的相关对象'postid'而导致数据丢失

华俊弼
2023-03-14

我有一个数据库(和模型)情况,如下模式所示:

这是ModelSerialize:

class PostCreateSerializer(serializers.ModelSerializer):
    base64image = serializers.CharField(allow_blank=True, required=False)
    categories = serializers.ListField(child=serializers.IntegerField(), required=False)

    class Meta:
        model = Post
        fields = ('title', 'text', 'base64image', 'categories')

    def create(self, validated_data):
       cats = None
       if 'categories' in validated_data:
           cats = validated_data.pop('categories')

       post = Post.objects.create(**validated_data)

       if cats is not None:
           for cat in cats:
               PostCategory.objects.create(postid=post, categoryid=Category.objects.get(id=cat), isprimary=False)

       return post

我将这个json发送到api方法

{
"title": "Post Test",
"text": "Body post Test",
"categories": [2,4]
}
ValueError: save() prohibited to prevent data loss due to unsaved related object 'postid'.

Internal Server Error: /api/post/create/
Traceback (most recent call last):
  File "/Users/alfdev/Lavori/PushApp/Rumorize/rvenv/lib/python3.4/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/alfdev/Lavori/PushApp/Rumorize/rvenv/lib/python3.4/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/alfdev/Lavori/PushApp/Rumorize/rvenv/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/alfdev/Lavori/PushApp/Rumorize/rvenv/lib/python3.4/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/alfdev/Lavori/PushApp/Rumorize/rvenv/lib/python3.4/site-packages/rest_framework/views.py", line 466, in dispatch
    response = self.handle_exception(exc)
  File "/Users/alfdev/Lavori/PushApp/Rumorize/rvenv/lib/python3.4/site-packages/rest_framework/views.py", line 463, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/alfdev/Lavori/PushApp/Rumorize/rvenv/lib/python3.4/site-packages/rest_framework/generics.py", line 192, in post
    return self.create(request, *args, **kwargs)
  File "/Users/alfdev/Lavori/PushApp/Rumorize/rvenv/lib/python3.4/site-packages/rest_framework/mixins.py", line 21, in create
    self.perform_create(serializer)
  File "/Users/alfdev/Lavori/PushApp/Rumorize/server/rumorize/contents/views.py", line 117, in perform_create
    PostCategory.objects.create(postid=x, categoryid=Category.objects.get(id=cat), isprimary=False)
  File "/Users/alfdev/Lavori/PushApp/Rumorize/rvenv/lib/python3.4/site-packages/django/db/models/manager.py", line 122, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/alfdev/Lavori/PushApp/Rumorize/rvenv/lib/python3.4/site-packages/django/db/models/query.py", line 401, in create
    obj.save(force_insert=True, using=self.db)
  File "/Users/alfdev/Lavori/PushApp/Rumorize/rvenv/lib/python3.4/site-packages/django/db/models/base.py", line 651, in save
    "unsaved related object '%s'." % field.name
ValueError: save() prohibited to prevent data loss due to unsaved related object 'postid'.

视图中我的post_create实现:

def perform_create(self, serializer):
# build and save the image
if 'base64image' in serializer.validated_data:
    base64_string = serializer.validated_data.pop('base64image')
    import base64
    import os
    import uuid

    base64_format, base64_string = base64_string.split(';base64,')
    base64_content = base64.b64decode(base64_string)
    filename = '{}{}'.format(uuid.uuid4(), utilities.file_extension_from_base64_format(base64_format))
    path = os.path.join(MEDIA_ROOT, 'post_photos')

    if not os.path.exists(path):
        os.makedirs(path)

    with open(os.path.join(path, filename), 'wb+') as f:
        f.write(base64_content)

    serializer.validated_data['image'] = filename

serializer.save(userid=self.request.user, updateuserid=self.request.user, state=1)

更新

现在我得到了这个错误:django.db.models.fields.related_descriptors.relatedObjectDoesNotexist:Post没有ID。

这些是我的模型:

class Post(models.Model):
id = models.BigIntegerField(db_column='ID', primary_key=True, editable=False)
title = models.CharField(db_column='Title', max_length=500)
text = models.TextField(db_column='Text')
createdate = models.DateTimeField(db_column='CreateDate', editable=False, default=datetime.datetime.now)
updatedate = models.DateTimeField(db_column='UpdateDate', blank=True, null=True, editable=False, default=datetime.datetime.now)
updateuserid = models.ForeignKey(User, models.DO_NOTHING, db_column='UpdateUserID', blank=True, null=True, related_name='PostUpdateUser')
userid = models.OneToOneField(User, models.DO_NOTHING, db_column='UserID', related_name='creation_user')
image = models.CharField(db_column='Image', max_length=500, blank=True, null=True)
state = models.SmallIntegerField(db_column='State')

class Meta:
    managed = False
    db_table = 'post'
    verbose_name = 'Post'
    verbose_name_plural = 'Posts'

类PostCategory(Models.Model):id=models.bigIntegerField(db_column='id',primary_key=true)#字段名小写。postid=models.foreignkey(Post,models.do_nothing,db_column='postid',related_name='posts_categories')#字段名小写。categoryid=models.foreignkey(Category,models.do_nothing,db_column='categoryid')#字段名小写。isprimary=models.booleanfield(db_column='isprimary')#字段名小写。此字段类型是一种猜测。

class Meta:
    managed = False
    db_table = 'post_category'

有什么建议吗?谢谢

共有1个答案

储俊英
2023-03-14

尝试调用ModelSerializerCreate方法,而不是自己创建对象。另外,if语句也不是必需的,对于PostCategory,您可以直接使用ID字段。

class PostCreateSerializer(serializers.ModelSerializer):
    base64image = serializers.CharField(allow_blank=True, required=False)
    categories = serializers.ListField(child=serializers.IntegerField(), required=False)

    class Meta:
        model = Post
        fields = ('title', 'text', 'base64image', 'categories')

    def create(self, validated_data):

       # you don't need the if block
       cats = validated_data.pop('categories', None)

       # try calling the create method of ModelSerializer
       post = super(PostCreateSerializer, self).create(validated_data)

       if cats is not None:
           for cat in cats:
               PostCategory.objects.create(postid_id=post.id, categoryid_id=cat, isprimary=False)

       return post
 类似资料:
  • 当我创建新的团队并试图将其关联到我的用户配置文件时,我发现这个错误正在显示。我想要一个团队,很多成员和只有一个创建者(或管理的团队),创建者也是小组的成员。如何将团队与用户配置文件关联? models.py views.py

  • p3=Place(name='Demon Dogs',address='944 W.Fullerton')restaurant.objects.create(Place=p3,serves_hot_dogs=true,serves_pizza=false) Traceback(最近调用为last): ... valueerror:save()禁止,以防止由于未保存的相关对象'Place'而丢失数据

  • 我试图使用inlineformset创建父模型和一些子模型。下面是我的观点。代码可以将初始Rfq模型保存到数据库中,但当它试图将行保存到InlineFormSet时会出错。这是一对多关系,但使用ForeignKey字段。 这是我的回溯

  • 问题内容: 我需要将新创建的主键传递给同一视图中的另一个表单字段,但是出现错误。有什么建议可以使这项工作吗?看起来就像过去,这就是答案: 根据文档,这就是较新的Django版本中发生的情况 p3 =地点(名称=``恶魔狗’‘,地址=‘944 W.富乐顿’)Restaurant.objects.create(地点= p3,serve_hot_dogs = True,serves_pizza = Fa

  • 我需要知道如何清除导致以下错误的未保存的相关数据: 禁止保存()以防止由于未保存的相关对象'order'而导致数据丢失。 我的代码按预期工作,但我未能完成一个订单。此后,任何保存新订单的尝试都会导致上述错误。我知道原因是对的更改,但肯定有一些方法可以通过日志之类的方式清除这些更改...我尝试重新创建数据库和sqlflush命令,但都不起作用。 视图 模型 表格

  • 我正在学习SpringJPA,我从将对象映射到表开始。我对OneToOne和OneToMany的关系没有问题,但我不太明白为什么我不能预先列出一个与许多关系相关的对象。我有一本可以有很多作者的书,还有一本可以有很多书的作者。通过中间表book_author正确生成模式(我可以在MySql Workbench中看到),但我得到以下示例: Hibernate:在作者(名字、姓氏)中插入值(?,) Hi