Created
August 14, 2018 17:20
-
-
Save anuj9196/12ebefe4a538882aa08c14abde9d3b5b to your computer and use it in GitHub Desktop.
serializer.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ContactSerializer(serializers.HyperlinkedModelSerializer): | |
phone_numbers = ContactPhoneNumberSerializer( | |
source='contactphonenumber_set', | |
many=True, | |
required=False | |
) | |
emails = ContactEmailSerializer( | |
source='contactemail_set', | |
many=True, | |
required=False | |
) | |
address = ContactAddressSerializer( | |
source='contactaddress_set', | |
many=True, | |
required=False | |
) | |
# primary_phone = serializers.SerializerMethodField() | |
url = serializers.HyperlinkedRelatedField( | |
view_name='contacts:detail', | |
read_only=True | |
) | |
amount_due = serializers.SerializerMethodField() | |
user = serializers.CurrentUserDefault() | |
class Meta: | |
model = Contact | |
fields = ('url', 'id', 'first_name', 'last_name', 'full_name', 'gender', 'date_of_birth', 'avatar', | |
'primary_phone', 'primary_email', 'phone_numbers', 'emails', 'address', 'amount_due', | |
'created', 'modified') | |
def get_amount_due(self, obj): | |
return AmountGiven.objects.amount_due(obj) | |
# def get_primary_phone(self, obj): | |
# primary_phone = obj.contactphonenumber_set.filter(primary=True).first() | |
# | |
# if primary_phone: | |
# return primary_phone.phone | |
# | |
# return None | |
# def amount_due(self, obj): | |
# return obj.amountgiven.amount_due() | |
def create(self, validated_data): | |
print(validated_data) | |
# print(**validated_data) | |
print(self.context['request'].user) | |
phone_numbers = validated_data.pop('contactphonenumber_set', None) | |
emails = validated_data.pop('contactemail_set', None) | |
addresses = validated_data.pop('contactaddress_set', None) | |
# user = self.context['request'].user | |
# user = validated_data.pop('user') | |
instance = Contact.objects.create( | |
# user=user, | |
**validated_data | |
) | |
if phone_numbers is not None: | |
for phone_data in phone_numbers: | |
ContactPhoneNumber.objects.create(contact=instance, **phone_data) | |
if emails is not None: | |
for email_data in emails: | |
ContactEmail.objects.create(contact=instance, **email_data) | |
if addresses is not None: | |
for address_data in addresses: | |
ContactAddress.objects.create(contact=instance, **address_data) | |
return instance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment