Django 模型在将数据插入模型时的值错误



我正在尝试使用APIView表单数据插入到模型UserUserGroup中。

class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=255, blank=False, null=False)
last_name = models.CharField(max_length=255, blank=False, null=False)
profile_picture = models.ImageField(upload_to='profile_pictures/', max_length=None, null=True, blank=True)
is_active = models.BooleanField(default=True)
objects = UserManager()
USERNAME_FIELD = 'email'

class UserGroup(models.Model):
user = models.ForeignKey(User, related_name='user_id', on_delete=models.CASCADE, blank=False)
role = models.ForeignKey(Role, related_name='role_id', on_delete=models.CASCADE, blank= False)

我可以将数据插入模型User,但当我尝试对模型UserGroup执行同样的操作时,它会返回一个错误。

ValueError: Cannot assign "17": "UserGroup.user" must be a "User" instance.

我希望这个API创建一个用户,并通过在模型UserGroup中插入role_iduser_id,立即将角色分配给新创建的用户。

我创建了两个不同的序列化程序UserSerializerUserGroup序列化程序,它们都有自己的创建方法来将实例推送到模型中。此外,在请求后有效载荷中,我接受User模型的所有字段,但对于UserGroup模型,我只接受role字段,而不接受user字段,因为一旦创建用户,就需要生成其值。

如果创建了用户,但API未能将角色分配给该用户,那么我也必须使用事务来回滚。所以,我想知道这是完成这项任务的合适方式吗。类UserAPIViews(APIView(:

permission_classes = [IsAuthenticated]
parser_classes = (FormParser, MultiPartParser)
def post(self, request, format=None):
user_group={} #dictionary for UserGroupSerializer
user_group['role'] = request.data['user_group'] # adding Role object to UserGroup dictionary from request payload.
del request.data['user_group'] # removing user_group (key,value) from the payload so that dictionary could used for UserSerializer
user_serialized_data = serializers.UserSerializer(data=request.data) # Serializing request payload dictionary with the UserSerializer
if user_serialized_data.is_valid(): # check the dictionary is validated or invalidated by the UserSerializer
try:
user_created_with_id = user_serialized_data.save() # if the dictionary is validated save the UserSerilaized instance to the User model.
# if the reqest payload dictionary is saved successfully then the save() will return the id of newly created object.
except IntegrityError as error:
message = f'Email already exist.'
return Response ({
'error_message' : message,
'status' : status.HTTP_226_IM_USED
})
else:
return Response ({'user_serilization_error':user_serialized_data.error_messages}) # return Payload dictionary has been invalidated by the UserSerilaizer.
# add the user parameter to the user_group dictionary. The value of key user should be the object id of newly created user.
user_group['user'] = user_created_with_id
# now the UserGroupSerilaizer dictionary is ready.
# user_group ={"user":user_created_with_id, "role":<Role: Role object (2)>} 
# serilaize the user_group dictionary with the UserGroupSerilaizer.
# this is where it generates a ValueError stating that UserGroup.user must be a User instance.
user_group_serialized_data = serializers.UserGroupSerializer(data=user_group)
if user_group_serialized_data.is_valid():
user_group_id = user_group_serialized_data.save()
success_message = 'User has been created.'
return Response({
'success_message' : success_message,
'status' : status.HTTP_201_CREATED
})
else:
return Response ({'user_group_serilization_error':user_serialized_data.error_messages})

UserGroupSerializer

class UserGroupSerializer(serializers.Serializer):
class Meta:
model = UserGroup
user = serializers.IntegerField(required=True)
role = serializers.IntegerField(required=True)
def create(self, validated_data):
user_role_relation_id = UserGroup.objects.create(**validated_data)
return user_role_relation_id

UserSerializer

class UserSerializer(serializers.Serializer):
class Meta:
model = User
id = serializers.IntegerField(read_only=True)
email = serializers.EmailField(required=True)
first_name = serializers.CharField(max_length=255, required=True)
last_name = serializers.CharField(max_length=255, required=True)
profile_picture = serializers.ImageField(max_length=None, allow_empty_file=True, use_url= False, required=False)
password = serializers.CharField(max_length = 255, write_only=True, required=True)
def create(self, validated_data):
user_id = User.objects.create_user(**validated_data)
return user_id

API请求的有效载荷如下所述-

{
"first_name":"", # Serialized by UserSerializer
"last_name":"", # Serialized by UserSerializer
"email":"", # Serialized by UserSerializer
"password":"", # Serialized by UserSerializer
"profile_picture":"", # Serialized by UserSerializer
"user_role:":"" # Serialized by UserGroupSerializer
}

我不得不将这个负载拆分为两个不同的字典,一个由UserSerializer序列化,另一个由UserGroupSerializer序列化。

请阅读APIView类的注释以了解流程。

ValueError:无法分配"17":"UserGroup.user"必须是"user"实例。该错误表示必须给用户实例作为输入UserGroup.user=用户对象

你可以通过:

current_user = User.objects.get(id = 17)
UserGroup.user = current_user 

UserGroup.user = request.user

问题似乎在UserGroupSerializer 中

你看过这个吗:https://www.django-rest-framework.org/api-guide/serializers/#dealing-带有嵌套对象

(你不应该调整

user_group['user']

很抱歉评论中的混乱(

最新更新