我正在尝试更新userprofile
实例。但是我没有在json中传递user_groups
,它从我的user_groups
字段中删除了所有外键。因此,我为此设置(尝试)-
if request.data.get('groups') == None:
print('Groups is None')
serializer2.instance.user_groups = userprofile.user_groups.all()
但是它给出了错误
直接分配给多对多集的正面是 禁止。请改用user_groups.set()
这是我要求输入错误的行
groups = serializers.PrimaryKeyRelatedField(source='user_groups', queryset=Groups.objects.all(), many=True, required=False)
但是它不起作用
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(userprofile)
serializer1 = EmployeeRegisterSerializer(user, data=request.data)
serializer2 = EmployeeProfileSerializerUpdate(userprofile, data=request.data)
if serializer1.is_valid() and serializer2.is_valid():
serializer1.save()
if request.data.get('groups') == None:
print('Groups is None')
serializer2.instance.user_groups = userprofile.user_groups.all()
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)
Serializer.py
class EmployeeProfileSerializerUpdate(serializers.ModelSerializer):
employee_id = serializers.CharField(source='user_employee_id', required=False)
payroll_id = serializers.CharField(source='user_payroll_id', required=False)
phone = serializers.CharField(source='user_phone', required=False)
hire_date = serializers.DateField(source='user_hire_date', required=False)
pay_rate = serializers.IntegerField(source='user_pay_rate', required=False)
salaried = serializers.CharField(source='user_salaried', required=False)
excempt = serializers.CharField(source='user_excempt', required=False)
state = serializers.CharField(source='user_state', required=False)
city = serializers.CharField(source='user_city', required=False)
zipcode = serializers.IntegerField(source='user_zipcode', required=False)
status = serializers.CharField(source='user_status', required=False)
groups = serializers.PrimaryKeyRelatedField(source='user_groups', queryset=Groups.objects.all(), many=True, required=False)
class Meta:
model = UserProfile
fields = [
'employee_id',
'phone',
'payroll_id',
'hire_date',
'pay_rate',
'salaried',
'excempt',
'state',
'city',
'zipcode',
'status',
'groups',
]