使用API​​View更新

时间:2019-03-25 09:00:45

标签: django django-rest-framework

我正在尝试更新Employee。为此,我使用了两个串行器,其中UserProfile模型与OneToOneField模型与User相关。但是问题是在更新时出现的。当我更新时,员工Serializer1在工作,但是serializer2在工作。我不知道是什么问题。

user_id = request.data['user_id'] 
        user = get_object_or_404(User, id=user_id)
        print(user)
        userprofile = get_object_or_404(UserProfile, user=user_id)
        print(request.data)
        serializer1 = EmployeeRegisterSerializer(user, data=request.data)
        serializer2 = EmployeeProfileSerializer(userprofile, data=request.data)

EmployeeProfileSerializer在更新时不起作用。添加员工时正在工作。但不是为了更新员工

class EmployeeUpdateApiV2(APIView):

    def post(self, request, *args, **kwrgs):

        try:
            accesstoken=AccessToken.objects.get(
                        token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '')
                    )
        except ObjectDoesNotExist:
            return Response (
                {
                    "status" : False,
                    "error" : "Wrong Access Token",
                    "error_message":"You have provided wrong access token.",
                }
            )

        user_id = request.data['user_id'] 
        user = get_object_or_404(User, id=user_id)
        print(user)
        userprofile = get_object_or_404(UserProfile, user=user_id)
        print(request.data)
        serializer1 = EmployeeRegisterSerializer(user, data=request.data)
        serializer2 = EmployeeProfileSerializer(userprofile, data=request.data)

        if serializer1.is_valid() and serializer2.is_valid():
            serializer1.save()
            serializer2.save()
            print('Inside Valid')
            return Response (
                    {
                        "status" : True,
                        "message":"Employee Updated Successfully.",
                        "api_name" : "EmployeeUpdateApiV2",
                        "result": serializer1.data,
                        "result1": serializer2.data,

                    }
                )
        print('Out Valid')
        print('serializer1 ', serializer1.errors)
        print('serializer2', serializer2.errors)
        return Response(status=status.HTTP_404_NOT_FOUND)

这些是我的Serilizers

class EmployeeProfileSerializer(serializers.ModelSerializer):
    employee_id = serializers.CharField(source='user_employee_id', required=False)
    payroll_id = serializers.CharField(source='user_payroll_id', required=False)
    hire_date = serializers.CharField(source='user_hire_date', required=False)
    pay_rate = serializers.CharField(source='user_pay_rate', required=False)
    salaried = serializers.CharField(source='user_salaried', required=False)
    excempt = serializers.CharField(source='user_excempt', required=False)
    groups = serializers.CharField(source='user_groups_id', required=False)
    state = serializers.CharField(source='user_state', required=False)
    city = serializers.CharField(source='user_city', required=False)
    zipcode = serializers.CharField(source='user_zipcode', required=False)
    status = serializers.CharField(source='user_status', required=False)
    phone = serializers.CharField(source='user_phone', required=False)
    class Meta:
        model = UserProfile
        fields = [  
                    'employee_id',
                    'phone', 
                    'payroll_id',
                    'hire_date',
                    'pay_rate',
                    'salaried',
                    'excempt',
                    'groups',
                    'state',
                    'city',
                    'zipcode', 
                    'status',

                ]

class EmployeeRegisterSerializer(serializers.ModelSerializer):   
    class Meta:
        model = User
        fields = ['first_name','last_name', 'email',]

UserProfile模型:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user_company = models.ForeignKey(Company, on_delete=models.CASCADE)
    user_role = models.ForeignKey(ACLRoles, on_delete=models.CASCADE)
    user_dob = models.DateField(null=True, blank=True)
    user_phone = models.CharField(max_length=30, blank=True, null=True)
    user_image = models.ImageField(upload_to='user_profiles/', default='default_user.png',blank=True, null=True)
    user_created = models.DateTimeField(auto_now_add=True)
    user_is_deleted = models.BooleanField(default=False)
    user_deleted_at = models.DateTimeField(blank=True, null=True)
    user_groups = models.ManyToManyField(Groups,related_name='user_groups')
MALE = 'Male'
    FEMALE = 'Female'
    GENDER_CHOICES = (
        (MALE, 'Male'),
        (FEMALE, 'Female'),
    )
    user_gender = models.CharField(
        max_length=8,
        choices=GENDER_CHOICES,
    )

    ACTIVE = 'Active'
    INACTIVE = 'Inactive'
    PENDING = 'Pending'
    USER_ACTIVE_CHOICES = (
        (ACTIVE, 'Active'),
        (INACTIVE, 'Inactive'),
        (PENDING, 'Pending'),
    )
    user_status = models.CharField(
        max_length=8,
        choices=USER_ACTIVE_CHOICES,
        default=ACTIVE,
    )



    # user_detail table in apollo database
    user_employee_id = models.CharField(max_length=30, blank=True, null=True)
    user_payroll_id = models.CharField(max_length=30, blank=True, null=True)
    user_pay_rate = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    HOURLY = 'Hourly'
    WEEKLY = 'Weekly'
    PAY_TYPE_CHOICES = (
        (HOURLY, 'Hourly'),
        (WEEKLY, 'Weekly'),
    )
    user_pay_type = models.CharField(
        max_length=8,
        choices=PAY_TYPE_CHOICES,
        blank= True,
        null = True
    )
    user_hire_date = models.DateField(null=True, blank=True)
    YES = 'Yes'
    NO = 'No'
    SALARY_TYPE_CHOICES = (
        (YES, 'Yes'),
        (NO, 'No'),
    )
    user_salaried = models.CharField(
        max_length=8,
        choices=SALARY_TYPE_CHOICES,
        blank= True,
        null = True
    )
    EXCEMPT_TYPE_CHOICES = (
        (YES, 'Yes'),
        (NO, 'No'),
    )
    user_excempt = models.CharField(
        max_length=8,
        choices=EXCEMPT_TYPE_CHOICES,
        blank= True,
        null = True
    )
    user_state = models.CharField(max_length=30, blank=True, null=True)
    user_city = models.CharField(max_length=30, blank=True, null=True)
    user_zipcode = models.IntegerField(blank=True, null=True)



    class Meta:
        db_table = "userprofile"

    def __str__(self):
        return self.user.email

    def save(self, *args, **kwargs):

        try:
            this = UserProfile.objects.get(id=self.id)

            if this.user_image != self.user_image and str(this.user_image) !='default_user.png':
                this.user_image.delete()

            super().save()

            img = Image.open(self.user_image.path)

            if img.height > 300 or img.width > 300 : 
                output_size = (250, 250)
                img.thumbnail(output_size)
                img.save(self.user_image.path)

        except: pass

        super(UserProfile, self).save(*args, **kwargs)




    def soft_delete(self):
        self.user_is_deleted = True
        self.user_deleted_at  = timezone.now() - tdelta(days=-1)
        self.save()

        self.user.is_active = False # This will not make user login
        self.user.save()

0 个答案:

没有答案