2

At the moment I developed the following code, for me to get the Contact List of each user. The views return the ID numbers of the Contacts of the User. I need to get, instead of the ID numbers, the 'name' and 'last_name' attribute of said contacts. I am quite new to Django's REST Framework and I'm not quite sure what to do next but I believe I have to nest the APIView. I would really appreciate some help!

views.py

def list_contacts(request, id_profile):
    url = request.build_absolute_uri(reverse('api_users:contact_list', kwargs={'pk':id_profile}))
    response = requests.get(url)
    profile = Profile.objects.get(pk=id_profile)
    if response.status_code == status.HTTP_200_OK:
        data = response.content
        user = json.loads(data)
        return render(request, 'profiles/contact_list.html', {'user':user})

models.py

class Profile(models.Model):
    id_user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birthday = models.DateField(auto_now=False)
    description = models.CharField(max_length=100)
    profile_picture = models.ImageField(upload_to='images/profiles/%Y/%m/%d', blank=False)
    active = models.BooleanField(default = False)
    contacts = models.ManyToManyField('self', blank=True, default='null')
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)
    deleted_at = models.DateTimeField(blank=True, null=True)

    class Meta:
        ordering = ('-id',)

    def __str__(self):
        return self.name+' '+self.last_name

    def active_profiles():
        return Profile.objects.filter(active=True)

api/views.py

class ContactListView(generics.ListAPIView):

queryset = Profile.objects.all()
serializer_class = UserContactListSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('name', 'last_name',)

def get(self, request, pk, format=None):
    contacts = Profile.objects.get(pk=pk)
    serializer = UserContactListSerializer(contacts)
    return Response(serializer.data)

api/serializers.py

class UserContactListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Profile
        fields = ['name','last_name','contacts']

1 Answer 1

4

I don't know what exactly is going on in your list_contacts but if you want to use the same serializer as a field in itself, you currently can't.
While Django models allow you to use 'self' as the reference, DRF doesn't.

What you can instead do is create another serializer and use that as the field.

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ("id", "first_name", "last_name")

class UserContactListSerializer(serializers.ModelSerializer):
     contacts = UserSerializer(many=True)

     class Meta:
         model = Profile
         fields = ("id", "first_name", "last_name", "contacts")
Sign up to request clarification or add additional context in comments.

2 Comments

wow. That was nice! Thanks! I just have another little question. When I show the result of the whole API it shows: {'NAME':'John','LAST_NAME':'Doe'} Do you know how to get rid of that?
Nvm. Solved it by adding {{user.contact.name}}

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.