Anuj TBE
Anuj TBE

Reputation: 9826

create multiple related object with Django REST Framework

I'm using Djago 2.0 and Django REST Framework

I have following model classes for contacts/models.py

class Contact(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100, blank=True, null=True)
    date_of_birth = models.DateField(blank=True, null=True)

class ContactPhoneNumber(models.Model):
    contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
    phone = models.CharField(max_length=100)
    primary = models.BooleanField(default=False)

contacts/views.py

class ContactViewSet(viewsets.ModelViewSet):
    serializer_class = ContactSerializer
    permission_classes = (IsAuthenticated, AdminAuthenticationPermission,)

    def get_queryset(self):
        return Contact.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(user_id=self.request.user)

and contacts/serializers.py is defined as

class ContactPhoneNumberSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContactPhoneNumber
        fields = ('id', 'phone', 'primary', 'created', 'modified')


class ContactSerializer(serializers.HyperlinkedModelSerializer):
    phone_numbers = ContactPhoneNumberSerializer(source='contactphonenumber_set', many=True)

    user = serializers.CurrentUserDefault()

    class Meta:
        model = Contact
        fields = ('url', 'id', 'first_name', 'last_name', 'date_of_birth', 'phone_numbers')

    def create(self, validated_data):
        phone_numbers = validated_data.pop('contactphonenumber_set')
        user = validated_data.pop('user_id')
        instance = Contact.objects.create(
            user=user,
            **validated_data
        )
        for phone_data in phone_numbers:
            ContactPhoneNumber.objects.create(contact=instance, **phone_data)
        return instance

I want to be able to create multiple phone_number instances with new contact object.

How can I pass multiple phone_numbers with fields phone, primary along with contact data?

Upvotes: 1

Views: 2043

Answers (1)

rtindru
rtindru

Reputation: 5357

Your JSON Post body needs to look like this:

{
    "user": 1,
    "first_name": "Anuj",
    "last_name": "TBE",
    "date_of_birth": "1990-01-01",
    "contactphonenumber_set": [
        {
            "phone": "+91999999999",
            "primary": false
        },
        {
            "phone": "+91999999993",
            "primary": true
        }
    ]
}

Do think about how you want to deal with duplicates in this context.

Upvotes: 2

Related Questions