class ContactRelationSeria lizer ReprSerializerMixin serializers Model

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class ContactRelationSerializer(ReprSerializerMixin, serializers.ModelSerializer):
contact = ContactSerializer()
def create(self, validated_data):
contact_data = validated_data.pop('contact')
contact_id = self.initial_data['contact'].get('id')
if contact_id:
# Contact relation is getting created for an existing contact. We allow to modify contact's fields
# before creating contact relation.
contact = Contact.objects.get(pk=contact_id)
for attr, value in contact_data.items():
setattr(contact, attr, value)
contact.save()
else:
# New contact relation and contact are getting created.
primary_organization = self.context['request'].primary_organization
contact = Contact.objects.create(organization=primary_organization, **contact_data)
return ContactRelation.objects.create(contact=contact, **validated_data)