首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >成功更新,但数据库中的数据未更新。Django rest框架

成功更新,但数据库中的数据未更新。Django rest框架
EN

Stack Overflow用户
提问于 2022-04-30 18:25:20
回答 1查看 363关注 0票数 0

我正在进行我的最后一年的项目,我需要一些帮助来理解实际发生的事情,的问题是:我通过postman访问了更新请求,这给出了更新数据的成功消息。但是,当我检查我的数据库时,没有更新的数据。我也做了调试,但也没有例外,我可以理解的问题,任何人都可以帮助我?我在用

PgAdmin用于我的数据库。

Django==4.0.2

djangorestframework==3.13.1

djangorestframework-jwt==1.11.0

djangorestframework-simplejwt==5.0.0

psycopg2==2.9.3**.

My Model:

代码语言:javascript
运行
复制
class Company(Base):
    company_name = models.CharField(max_length=255, db_column='Company_Name')
    company_email = models.EmailField(unique=True, max_length=255, db_column='company_email')
    company_manager_name = models.CharField(max_length=255, db_column='Manager_Name')
    company_address = models.CharField(max_length=255, db_column='Company_address')
    about_company = models.TextField()
    company_website = models.URLField(max_length=200)
    is_active = models.BooleanField(default=True, db_column='IsActive', help_text='I will use this for enable/disable '
                                                                                  'a specific record')

    class Meta:
        db_table: 'Company'

    def __str__(self):
        return self.company_name

    def save(self, *args, **kwargs):
        try:
            if not self.pk:
                self.company_email = self.company_email.replace(" ", "").lower()
                super().save()
        except Exception:
            raise
代码语言:javascript
运行
复制
class Base(models.Model):
    """Following fields are abstract and will be use in All over the project Any time Anywhere"""
    create_by = models.BigIntegerField(db_column='CreatedBy', null=True, blank=True, default=0)
    create_on = models.DateTimeField(db_column='CreatedOn', auto_now_add=True)
    modified_by = models.BigIntegerField(db_column='ModifiedBy', null=True, blank=True, default=0)
    modified_on = models.DateTimeField(db_column='ModifiedOn', auto_now=True)
    deleted_by = models.BigIntegerField(db_column='DeletedBy', null=True, blank=True, default=0)
    deleted_on = models.DateTimeField(db_column='DeletedOn', auto_now=True)
    status = models.BigIntegerField(db_column='Status', default=0, help_text='I will use this field for making'
                                                                             'the status like pending approved and '
                                                                             'for some other purpose by Default it is '
                                                                             'Zero which has no meaning', )

    class Meta:
        abstract: True

serializer.py:

代码语言:javascript
运行
复制
class CompanyUpdateSerializer(serializers.ModelSerializer):
    company_name = serializers.CharField(required=True, allow_null=False, allow_blank=False)
    company_email = serializers.CharField(required=True, allow_null=False, allow_blank=False)
    company_manager_name = serializers.CharField(required=True, allow_null=False, allow_blank=False)
    company_address = serializers.CharField(required=True, allow_null=False, allow_blank=False)
    about_company = serializers.CharField(required=True, allow_null=False, allow_blank=False)
    company_website = serializers.URLField(allow_blank=False, allow_null=False)

    class Meta:
        model = Company
        fields = ['id', 'company_name', 'company_email', 'company_manager_name', 'company_address', 'about_company',
                  'company_website']

    def update(self, instance, validated_data):
        try:
            instance.company_name = validated_data.get('company_name', instance.company_name)
            instance.company_email = validated_data.get('company_email', instance.company_email)
            instance.company_manager_name = validated_data.get('company_manager_name', instance.company_manager_name)
            instance.company_address = validated_data.get('company_address', instance.company_address)
            instance.about_company = validated_data.get('about_company', instance.about_company)
            instance.company_website = validated_data.get('company_website', instance.company_website)
            instance.save()

            return instance
        except Exception as e:
            raise e

Views.py

代码语言:javascript
运行
复制
    def put(self, request, pk=None):
        try:
            id1 = pk
            saved_company = Company.objects.get(pk=id1)
            data = request.data
            serializer = CompanyUpdateSerializer(instance=saved_company, data=data)
            if serializer.is_valid():
                serializer.save()
                return self.send_response(success=True, code=f'200', status_code=status.HTTP_200_OK,
                                          description='Company is updated')
            return self.send_response(code=f'422', status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                                      description=serializer.errors)
        except ObjectDoesNotExist:
            return self.send_response(code='422', status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                                      description="No Company matches the given query.")
        except IntegrityError:
            return self.send_response(code=f'422', status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                                      description="Email Already Exist")
        except Company.DoesNotExist:
            return self.send_response(code=f'422', status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                                      description="Company Model doesn't exists")
        except FieldError:
            return self.send_response(code=f'500', description="Cannot resolve keyword given in 'order_by' into field")
        except Exception as e:
            return self.send_response(code=f'500', description=e)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-01 02:51:42

问题来自于Company.save()方法。

你骑过去就像

代码语言:javascript
运行
复制
class Company(Base):
    ...

    def save(self, *args, **kwargs):
        try:
            if not self.pk:
                self.company_email = self.company_email.replace(" ", "").lower()
                super().save()
        except Exception:
            raise

注意super().save()self.pk中的调用是None if语句块。

这将使实际的保存方法只在pkNone时才被调用,这意味着只有在创建新实例时才调用,而不是在更新实例时调用。

super().save()调用移到if语句之外,应该同时处理创建和更新。

代码语言:javascript
运行
复制
class Company(Base):
    ...

    def save(self, *args, **kwargs):
        try:
            if not self.pk:
                self.company_email = self.company_email.replace(" ", "").lower()
            super().save(*args, **kwargs)
        except Exception:
            raise
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72071092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档