0
\$\begingroup\$

I'm using DRF. I have a User model and contacts field in it and contacts are also User instances.

class User(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(
        _("first name"),
        max_length=30,
        blank=True,
    )
    last_name = models.CharField(
        _("last name"),
        max_length=150,
        blank=True,
    )
    phone_number = PhoneNumberField(
        unique=True,
        blank=False,
        null=True
    )
    contacts = models.ManyToManyField("User", blank=True)

This is the serializer.

class AddContactSerializer(serializers.Serializer):
    phone_number = serializers.CharField(max_length=12, write_only=True, required=True)

    def update(self, instance, validated_data):
        user = self.context['request'].user
        phone_number = validated_data["phone_number"]
        added_contact = User.objects.get(phone_number=phone_number)
        user.contacts.add(added_contact)
        return UserSerializer(added_contact)

And the view.

class AddContact(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        serializer = AddContactSerializer(
            request.user, data=request.data, context={"request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(data=serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

I'll need to add error handling though.

Thank you for reviewing this.

\$\endgroup\$
2
  • \$\begingroup\$ On the code review site the code must be working as expected, which means that you must of tested the code. The title indicates that the code hasn't been tested yet. Please read How do I ask a good question?. \$\endgroup\$
    – pacmaninbw
    Sep 26, 2022 at 15:00
  • \$\begingroup\$ The code works as expected. I just want to know if this is a good way of adding a contact in this case. \$\endgroup\$ Sep 26, 2022 at 15:08

0

Your Answer

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

Browse other questions tagged or ask your own question.