1

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?

3
  • Is your question "how does the JSON object look" that you need to POT to this endpoint? Commented May 16, 2018 at 17:13
  • may be. At present, I'm using Postman to test API endpoints. This is my first API application, so no idea on how exactly multidimensional request data is formatted Commented May 16, 2018 at 17:15
  • Can you add the latest working JSON Post body ? Commented May 16, 2018 at 17:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

You get it right. Earlier I was geting same error to set queryset or read-only. I was confused about how to set queryset and where, so I added read-only. Can you update your answer with queryset implementation.
why objects.all() will not it expose all contacts even if they are not associated with current user. can we use filter() or it is required to use all() here?
Also it gives error as TypeError: __init__() got an unexpected keyword argument 'queryset'
@AnujTBE Your current implementation should work; my bad for raising a non-issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.