27๐
you can do it with SerializerMethodField
Example :
class PostSerializer(serializers.ModelSerializer):
fav = serializers.SerializerMethodField('likedByUser')
def likedByUser(self, obj):
request = self.context.get('request', None)
if request is not None:
try:
liked=Favorite.objects.filter(user=request.user, post=obj.id).count()
return liked == 1
except Favorite.DoesNotExist:
return False
return "error"
class Meta:
model = Post
then you should call serializer from view like this:
class PostView(APIVIEW):
def get(self,request):
serializers = PostSerializer(PostObjects,context={'request':request})
๐คrapid2share
8๐
Iโd be inclined to try and put as much of this as possible on the Like
model object and then bung the rest in a custom serializer field.
In serializer fields you can access the request
via the context
parameter that they inherit from their parent serializer.
So you might do something like this:
class LikedByUserField(Field):
def to_native(self, article):
request = self.context.get('request', None)
return Like.user_likes_article(request.user, article)
The user_likes_article
class method could then encapsulate your prefetching (and caching) logic.
I hope that helps.
๐คCarlton Gibson
- Django REST Framework (ModelViewSet), 405 METHOD NOT ALLOWED
- Django: updating a column, saved in a variable name
- Using APITestCase with django-rest-framework
- Serving static files on Django production tutorial
1๐
According to the Django Documentation โ SerializerMethodField, I had to change the code of rapid2share slightly.
class ResourceSerializer(serializers.ModelSerializer):
liked_by_user = serializers.SerializerMethodField()
def get_liked_by_user(self, obj : Resource):
request = self.context.get('request')
return request is not None and obj.likes.filter(user=request.user).exists()
๐คTobias Ernst
- How to change my django server time
- Django admin, section without "model"?
- Django HTML E-mail template doesn't load css in the e-mail
- Token Authentication Django Rest Framework HTTPie
- Django dev server intermittently fails to serve static files
Source:stackexchange.com