我在更新一个嵌套对象时遇到了一个问题,所以我有两个模型,它们的结构和这个相似:
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表。我认为下面的逻辑是正确的,但它遗漏了一些东西。任何帮助都将非常感谢。有人能帮助吗?
2条答案
按热度按时间5uzkadbs1#
看看此更新方法是否更适合您:
有两点需要注意:我将
instance.save()
移到了末尾。在您的测试用例中,您在添加/编辑员工之前保存了示例。其次,在您的测试用例中,您为employee_event_users
分配了一个字典类型的对象,而不是它所期望的实际对象。您可以修改您的测试用例,其中您创建了新用户,将其添加到列表中,然后保存(如果您不想删除子项,然后重新添加它们)。下面是它的外观:r6hnlfcb2#
这是一种很老套的方法,但很有效。可能不是一个干净的解决方案。