I have the following code
serializer.py
class ContactSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
many = kwargs.pop('many', True)
many = True
super(ContactSerializer, self).__init__(many=many, *args, **kwargs)
class Meta:
model = Contact
def validate(self, attrs):
# Check that the user in contact isn't the same as the parent user
if 'user' in attrs.keys() and 'parent_user' in attrs.keys() and attrs['user']:
if attrs['user'].pk == attrs['parent_user'].pk:
raise serializers.ValidationError("You can't add yourself as a contact")
return attrs
views.py
class ContactViewSet(viewsets.ModelViewSet):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated, )
def get_queryset(self):
return Contact.objects.filter(parent_user=self.request.user.pk)
def create(self, request):
if isinstance(request.DATA, list):
for i, contact_data in enumerate(request.DATA):
# Get the user id from the request
request.DATA[i]['parent_user'] = self.request.user.pk
# Check if the contact is aleardy a user
if 'email' in contact_data:
try:
request.DATA[i]['user'] = User.objects.get(email=contact_data['email']).pk
except User.DoesNotExist, e:
pass
return super(ContactViewSet, self).create(request)
Now the problem with this is that when I send a list of contacts in POST None of the objects are created, it just sends the error for the invalid objects. For example:
POST
[
{
"first_name": "Eyad",
"last_name": "tttttt",
"email": "[email protected]"
},
{
"first_name": "Eyad",
"last_name": "mmmmmm",
"email": "[email protected]"
}
]
The return
[
{},
{
"non_field_errors": [
"You can't add yourself as a contact"
]
}
]
How can I make this return something like this:
[
{
"created": true
},
{
"non_field_errors": [
"You can't add yourself as a contact"
]
}
]
This way when the API is called, valid objects are created and the API caller won't have to send those objects again.