0

I need to show user info in my post as nested json.

Models:

Profile

# Django
from django.db import models

class Profile(HelperModel):
    """ User Profile

    UserProfile provides the principal fields for the user participation
    in addition using proxy model that extends the base data with other
    information.
    """

    user = models.OneToOneField(
        'authentication.User', on_delete=models.CASCADE)
    avatar = models.ImageField(
        upload_to='authentication/pictures/users',
        blank=True,
        null=True
    )
    def __str__(self) -> str:
        """Return username"""
        return self.user.username

Post

# Django
from django.db import models
from zivo_app.apps.authentication.models.profiles import Profile

class Post(HelperModel):

    '''
    Implements the logic of post, this is a main model,
    inside save all the field logic for their correctly
    works. 
    Extends authentication lawyer models.
    '''
    title = models.CharField(max_length=130)
    error_code = models.CharField(max_length=150, blank=True)
    brief = models.TextField(max_length=250)
    avatar = models.ImageField(
        upload_to='blog/pictures/cover',
        blank=True,
        null=True
    )

    # FK
    user = models.ForeignKey(
        Profile,
        related_name='profiles',
        on_delete=models.CASCADE,
        verbose_name=("User Profile")
    )

Serializers:

ProfileSerializer

"""Profile serializer."""

# Django REST Framework
from rest_framework import serializers

# Models
from ..models.profiles import Profile


class ProfileModelSerializer(serializers.ModelSerializer):
    """Profile model serializer."""

    class Meta:
        """Meta class."""

        model = Profile
        fields = '__all__'

PostSerializer

'''
List all post in home level
'''

# Django REST Framework
from rest_framework import serializers

# Models
from ...models.post.post import Post


class ListPostSerializer(serializers.ModelSerializer):
    profiles = serializers.StringRelatedField(many=True)

    class Meta:
        model = Post
        fields = ['title', 'error_code', 'brief', 'avatar', 'profiles']

Views:

''' View of list post'''
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.decorators import api_view
from ...models.post.post import Post

from ...serializers.post.list_post_serializer import ListPostSerializer


@api_view(['GET'])
def getData(request):
    posts = Post.objects.all()
    serializer = ListPostSerializer(posts, many=True)
    return Response(serializer.data)

So when i make request, i get the next error:

AttributeError at /api-blog/home

I've tried this:

'''
List all post in home level
'''

# Django REST Framework
from rest_framework import serializers

# Models
from ...models.post.post import Post


class ListPostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = '__all__'
        depth = 1

and did works, but get all data and i only need specific attributes.

Output of request:

[
    {
        "id": 1,
        "created": "2023-05-17T03:43:17.385335Z",
        "modified": "2023-05-17T03:43:17.385352Z",
        "title": "Warning Partitioning Datastage",
        "error_code": "",
        "brief": "Warning: A sequential operator cannot preserve the partitioning of input data set",
        "avatar": "/media/blog/pictures/cover/wordle_3.png",
        "user": {
            "id": 1,
            "created": "2023-04-27T15:42:40.152401Z",
            "modified": "2023-04-27T15:42:40.152416Z",
            "avatar": "/media/authentication/pictures/users/profile_jcarrillo.jpg",
            "user": 2,
            "status": 1,
            "technology": 6,
            "rol": 2
        },
    }
]

I don´t know how to display serializer data in my view. I read serializer_relations and apply StringRelatiedField and it didn't works, SlugRelatedField and it didn't work either.

Please,how to achieve this? thanks =)

1 Answers1

0

Just update your serializers like below and it works

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ['avatar', 'user']

class ListPostSerializer(serializers.ModelSerializer):
    user = ProfileSerializer()#this fetch specific attribute as you want

    class Meta:
        model = Post
        fields = ['title', 'error_code', 'brief', 'avatar', 'user']