Django-Rest-Framework,正在更新两个表

piztneat  于 2023-01-06  发布在  Go
关注(0)|答案(2)|浏览(150)

我在更新一个嵌套对象时遇到了一个问题,所以我有两个模型,它们的结构和这个相似:

class EmployeeEvent(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
event_name = models.CharField(max_length=200)
start_date = models.DateField()
end_date = models.DateField()

class EmployeeEvent_Users(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
employee_event = models.ForeignKey(EmployeeEvent, on_delete=models.CASCADE,  related_name='employee_event_employee_list')

employee = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='employeeEvent_employee')

我编写了以下序列化程序:

class EmployeeEventUserSerializer(serializers.ModelSerializer):
class Meta:
    model = EmployeeEvent_Users
    fields = ('id', 'employee',)

class EmployeeEventSerializer(serializers.ModelSerializer):
employee_event_users = EmployeeEventUserSerializer( required=True, many=True)

class Meta:
    model = EmployeeEvent
    fields = ('event_name', 'start_date', 'end_date', 'employee_event_users', )

def create(self, validated_data):
    request = self.context.get('request')
    employee_event = EmployeeEvent.objects.create(
        event_name=validated_data['event_name'],
        start_date=validated_data['start_date'],
        end_date=validated_data['end_date'],
        # etc ...
    )
    employeeEventUsers_data = validated_data.pop('employee_event_users', [])

    for employeeEventUser_data in employeeEventUsers_data:
        employeeEvent_users = EmployeeEvent_Users.objects.create(
            employee_event=employee_event,
            employee=employeeEventUser_data['employee'],

        )
    employee_event.employee_event_users = employeeEventUsers_data;
    return employee_event

def update(self, instance, validated_data):

    instance.event_name = validated_data['event_name']
    instance.start_date = validated_data['start_date']
    instance.end_date = validated_data['end_date']
    instance.save()

    instance.employee_event_users = validated_data.get('employee_event_users')

    if instance.employee_event_users:
        for employee_event_user in instance.employee_event_users:
            employee_event_user_id = employee_event_user.get('employee_id', None)
            if employee_event_user_id:
                emp_user = EmployeeEvent_Users.objects.get(id=employee_event_user_id, employee_event=instance)
                emp_user.employee = employee_event_user.get('employee', emp_user.employee)
                emp_user.save()
            else:
                EmployeeEvent_Users.objects.create(employee_event=instance, **employee_event_user)

    return instance

到目前为止,创建工作正常,更新不工作。EmployeeEvent表正确更新,但没有更新EmployeeEvent_User表。我认为下面的逻辑是正确的,但它遗漏了一些东西。任何帮助都将非常感谢。有人能帮助吗?

5uzkadbs

5uzkadbs1#

看看此更新方法是否更适合您:

def update(self, instance, validated_data):
    instance.event_name = validated_data['event_name']
    instance.start_date = validated_data['start_date']
    instance.end_date = validated_data['end_date']

    # When updating children, I find it easier to delete them all
    # and then re-add them instead of checking each one. It probably
    # is not very efficient, however for small lists it should not
    # matter much.
    for emp in instance.employee_event_users.all():
      emp.delete()

    # Now go through and re-add the EmployeeEvent_User
    for employee_event_user in validated_data['employee_event_users']:
        user = EmployeeEvent_Users.objects.create(employee_event=instance, **employee_event_user)
        instance.employee_event_users.add(user)

    instance.save()
    return instance

有两点需要注意:我将instance.save()移到了末尾。在您的测试用例中,您在添加/编辑员工之前保存了示例。其次,在您的测试用例中,您为employee_event_users分配了一个字典类型的对象,而不是它所期望的实际对象。您可以修改您的测试用例,其中您创建了新用户,将其添加到列表中,然后保存(如果您不想删除子项,然后重新添加它们)。下面是它的外观:

def update(self, instance, validated_data):
    instance.event_name = validated_data['event_name']
    instance.start_date = validated_data['start_date']
    instance.end_date = validated_data['end_date']

    for employee_event_user in validated_data['employee_event_users']:
        employee_event_user_id = employee_event_user.get('employee_id', None)
        if employee_event_user_id:
            emp_user = EmployeeEvent_Users.objects.get(id=employee_event_user_id, employee_event=instance)
            emp_user.employee = employee_event_user.get('employee', emp_user.employee)
            emp_user.save()
        else:
            user = EmployeeEvent_Users.objects.create(employee_event=instance, **employee_event_user)
            user.save()
            instance.employee_event_users.add(user)

    instance.save()
    return instance
r6hnlfcb

r6hnlfcb2#

这是一种很老套的方法,但很有效。可能不是一个干净的解决方案。

@api_view(('PATCH',))
@permission_classes([IsAuthenticated, ])
def update_employer_profile(request):

    user_id = request.user.id

    request.data._mutable = True
    request.data['employer_user'] = user_id

    # Employer Details Table
    database_row_1 = TblEmployerDetails.objects.get(
        employer_user=user_id)

    employer_details_serialiser = TblEmployerDetailsSerializer(
        instance=database_row_1, data=request.data)

    user_serializer = UserSerializer(request.user, data=request.data, partial=True)

    # User Table
    if user_serializer.is_valid():
        user_serializer.save()

        # Employer Details Table
        if employer_details_serialiser.is_valid():
            employer_details_serialiser.save()

            updated = {**employer_details_serialiser.data, **user_serializer.data}

            return Response(updated, status=status.HTTP_200_OK)

        else:
            return Response(employer_details_serialiser.errors, status=status.HTTP_404_NOT_FOUND)

    else:
        return Response(user_serializer.errors, status=status.HTTP_404_NOT_FOUND)

相关问题