Bryar
Bryar

Reputation: 131

Cant access username of objects from queryset in Django

I have been struggling with this for a while now.

In my js code i fetch with a get request all the posts that users have made. In my django code,i query db for said posts. When i get the queryset of results, that is passed to the js code, where i try to access each object's author (user who posted it) in order to display it. But instead im given the pk, not the username.

So basically, I dont know how to get the username as the author (user who made the post) of each object, instad of the pk.

models.py:

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE) ##
    content = models.TextField(max_length=400, blank=False)
    date_posted = models.DateTimeField(auto_now_add=True)

    @property
    def username(self):
        return self.author.username

    def __int__(self):
        return self.

serializers.py :

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

js code:

function show_posts(sort) {

    fetch(`api/post-list/${sort}`)
    .then(response => response.json())
    .then(posts => {
      
      //for each email
      console.log(posts);
      posts.forEach(post => update_posts(post, sort));
  
    }); 
}

function update_posts(post, sort) {

    const element = document.createElement('div');
    element.setAttribute("class", "post-dv");

    console.log(post);

    element.innerHTML += "Author: " + post.author + "<br>"; 
    element.innerHTML += "Content: " + post.content + "<br>";
    element.innerHTML += "Date: " + post.date_posted + "<br>";
    element.innerHTML += "Likes: 0"  + "<br>"; 

document.querySelector('#posts-view').append(element);
}

views.py function:

@api_view(['GET'])
def postList(request, sort):
    if sort == "all":
        posts = Post.objects.all().order_by('-date_posted')
        for post in posts:
            username = User.objects.get(username=post.author)
            post.author = username
            #print(post.author)
    else:
        try:
            user = User.objects.get(username=sort)
            posts = Post.objects.filter(author=user).order_by('-date_posted')
        except User.DoesNotExist:
            #return JsonResponse({"error": "User doesn't exist."}, status=400)
            return Response(status=status.HTTP_400_BAD_REQUEST)
            print(f"POSTS: {posts}")


    serializer = PostSerializer(posts, many=True)

    return Response(serializer.data)

at views.py the serializer.data is like this. Can i only change the author value only by going through the posts with loops? Or can i modify something else somehow?

[OrderedDict([('id', 18), ('content', 'nn'), ('date_posted', '08/13/2020 08:54:23'), ('author', 1)]), OrderedDict([('id', 17), ('content', 'M'), ('date_posted', '08/13/2020 08:42:21'), ('author', 1)]), OrderedDict([('id', 16), ('content', '6'), ('date_posted', '08/13/2020 08:27:42'), ('author', 1)]), OrderedDict([('id', 15), ('content', '1'), ('date_posted', '08/12/2020 19:24:54'), ('author', 1)]), OrderedDict([('id', 14), ('content', '11'), ('date_posted', '08/12/2020 19:24:23'), ('author', 1)]), OrderedDict([('id', 13), ('content', '222'), ('date_posted', '08/12/2020 19:23:48'), ('author', 1)]), OrderedDict([('id', 12), ('content', '33'), ('date_posted', '08/12/2020 19:23:31'), ('author', 1)]), OrderedDict([('id', 11), ('content', '4'), ('date_posted', '08/12/2020 19:23:09'), ('author', 1)]), OrderedDict([('id', 10), ('content', '11'), ('date_posted', '08/12/2020 19:21:48'), ('author', 1)]), OrderedDict([('id', 9), ('content', '1'), ('date_posted', '08/12/2020 19:19:32'), ('author', 1)]), OrderedDict([('id', 8), ('content', '5'), ('date_posted', '08/12/2020 19:18:34'), ('author', 1)]), OrderedDict([('id', 7), ('content', '4'), ('date_posted', '08/12/2020 19:18:10'), ('author', 1)]), OrderedDict([('id', 6), ('content', '7'), ('date_posted', '08/12/2020 19:17:10'), ('author', 1)]), OrderedDict([('id', 5), ('content', '5'), ('date_posted', '08/12/2020 19:13:54'), ('author', 1)]), OrderedDict([('id', 4), ('content', '7'), ('date_posted', '08/12/2020 19:10:11'), ('author', 1)]), OrderedDict([('id', 3), ('content', '2'), ('date_posted', '08/12/2020 18:46:23'), ('author', 1)]), OrderedDict([('id', 2), ('content', '6'), ('date_posted', '08/12/2020 18:33:55'), ('author', 1)]), OrderedDict([('id', 1), ('content', '0'), ('date_posted', '08/12/2020 13:59:46'), ('author', 1)])]

Upvotes: 0

Views: 260

Answers (1)

ruddra
ruddra

Reputation: 52028

You can update your serializer like this(using SerializerMethodField):

class PostSerializer(serializers.ModelSerializer):
    username = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = '__all__'
    
    def get_username(self, obj):
       return obj.username

Which will allow you to access username value from the object.

There are alternative solutions as well, like using source:

class PostSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='username')

Upvotes: 1

Related Questions