I have UserSerializer and nested UserClientSerializer. I'm trying to update info for logged user. But I receive unique_together validation error.
I have the following models: models.py
class UserClients(models.Model):
user = models.ForeignKey(User, related_name='user_clients')
client = models.ForeignKey(Client, related_name='client_users')
belongs_to = models.BooleanField(default=False)
for_future = models.BooleanField(default=False)
class Meta:
unique_together = ('user', 'client')
Also I have two seralizers. serializers.py
class UserClientsSerializer(serializers.ModelSerializer):
class Meta:
model = UserClients
class UserSerializer(serializers.ModelSerializer):
user_clients = UserClientsSerializer(required=False, allow_null=True, many=True)
class Meta:
model = get_user_model()
exclude = ('password','username', 'date_joined', 'is_superuser')
@transaction.atomic
def create(self, validated_data):
...
@transaction.atomic
def update(self, instance, validated_data):
...
views.py
class CurrentUserDetails(RetrieveUpdateAPIView):
serializer_class = UserSerializer
permission_classes = (IsAuthenticated,)
def get_object(self):
return self.request.user
So, when I trying to update my user data, for example "belongs_to" was False, I want to change it to False. My my JSON data is like this.
{
"user_clients": [
{
"id": 57,
"belongs_to": true,
"for_future": false,
"user": 25,
"client": 3
}
]
}
but i receive validation error like this
{
"user_clients": [
{
"non_field_errors": [
"The fields user, client must make a unique set."
]
}
]
}
Do you have any idea about this problem?
The second post down on this link seems like it might describe a similar problem and a potential workaround that should work for you:
https://github.com/tomchristie/django-rest-framework/issues/2380
It seems like you are trying to create a new object rather than updating the old object which is why you are getting the unique together error.
If that is not the case then try turning off validation and using your own as described in the above link.