Created
June 24, 2014 17:59
-
-
Save maryokhin/51e3adef66cae714e9e9 to your computer and use it in GitHub Desktop.
No way to insert a custom serializer inside a model serializer?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from rest_framework import serializers | |
from rest_framework.serializers import ModelSerializer, Serializer | |
from api.models import Subscriber | |
from api.models.channel import Channel | |
from api.util.connection import get_redis_connection | |
from api.util.field import ReverseField | |
class ChannelStatsSerializer(Serializer): | |
""" | |
Serializer for embedding channel stats in channel object. | |
""" | |
subscriber_count = serializers.SerializerMethodField('get_subscriber_count') | |
post_count = serializers.SerializerMethodField('get_post_count') | |
def get_subscriber_count(self, channel): | |
redis_server = get_redis_connection() | |
return redis_server.llen('subscriber:{}'.format(channel.id)) | |
def get_post_count(self, channel): | |
redis_server = get_redis_connection() | |
return redis_server.llen('channelfeed:{}'.format(channel.id)) | |
class ChannelSerializer(ModelSerializer): | |
""" | |
Serializer for retrieving and updating channel information. | |
""" | |
url = ReverseField(view_name='channel-instance') | |
posts_url = ReverseField(view_name='channel-post-list') | |
privileges_url = ReverseField(view_name='channel-privilege-list') | |
subscribers_url = ReverseField(view_name='channel-subscriber-list') | |
stats = ChannelStatsSerializer(read_only=True) | |
current_user_is_subscribed = serializers.SerializerMethodField('is_current_user_subscribed') | |
class Meta(): | |
model = Channel | |
read_only_fields = ('date_created', ) | |
non_native_fields = ('stats', ) | |
exclude = ('subscribers', ) | |
def is_current_user_subscribed(self, channel): | |
""" | |
Check if the current logged in user is subscribed to this channel or not. | |
""" | |
request = self.context.get('request', None) | |
user = request.user | |
if user.is_authenticated(): | |
return Subscriber.objects.filter(user=user, channel=channel).exists() | |
else: | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment