Django序列化器报错:'TweetSerializer'无'get_likes'属性求助
Hey there, let's get this AttributeError sorted out quickly!
The Root Cause
When you use serializers.SerializerMethodField() in your Django REST Framework serializer, the framework automatically looks for a method named get_<your_field_name> to populate that field's value. Since you added the likes field but didn't define a get_likes method in your TweetSerializer, DRF throws that error because it can't find the method it needs to fetch the likes data.
The Fix: Add the get_likes Method
You just need to add a get_likes method to your TweetSerializer class. This method will take two parameters: self (the serializer instance) and obj (the individual Tweet object being serialized), and return the data you want for the likes field.
Here's how to implement it based on common use cases:
Example 1: Return the number of likes for the tweet
If your Tweet model has a ManyToManyField for likes (linked to the User model), you can return the count of users who liked the tweet:
# serializers.py from rest_framework import serializers from .models import Tweet class TweetSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField(read_only=True) class Meta: model = Tweet fields = ['id', 'content', 'author', 'likes', 'created_at'] # Required method for the SerializerMethodField def get_likes(self, obj): # Return the total number of likes return obj.likes.count()
Example 2: Return whether the current user liked the tweet
If you want to show if the logged-in user has liked the tweet, you can access the request from the serializer's context (make sure to pass the request to the serializer first):
# serializers.py class TweetSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField(read_only=True) class Meta: model = Tweet fields = ['id', 'content', 'author', 'likes', 'created_at'] def get_likes(self, obj): # Get the current user from the request in the serializer context current_user = self.context.get('request').user # Return True if the user liked the tweet, False otherwise return obj.likes.filter(id=current_user.id).exists()
To pass the request to the serializer's context (required for Example 2), update your view to include it:
# views.py from rest_framework import viewsets from .models import Tweet from .serializers import TweetSerializer class TweetViewSet(viewsets.ModelViewSet): queryset = Tweet.objects.all() serializer_class = TweetSerializer def get_serializer_context(self): # Pass the request to the serializer context return {'request': self.request}
Quick Checks to Ensure Success
- Double-check that your
Tweetmodel actually has alikesfield (e.g.,ManyToManyField(User, related_name='liked_tweets', blank=True)). - Make sure the method name is exactly
get_likes(lowercase, matches your field name withget_prepended—spelling matters here!). - If you're accessing the current user, confirm the request is being passed to the serializer's context (as shown in Example 2's view code).
Once you add this method, your serializer will be able to populate the likes field correctly, and the AttributeError should disappear.
内容的提问来源于stack exchange,提问作者flyhiee official

