I want to create a udemy like web app and using django rest framework for the backend and mysql as database. i have a model named 'Lessons' that contains list of all lessons and one of the fields is 'video-link'. also i have another model names Purchases that have two ForeignKey fields :Users and Lessons. i want to show the Lessons to all users but for the download field i have to lookup the pair (User , Lesson) in Purchases and if He has the course i will show him the download field.
My View Set
class LessonsViewSet(viewsets.ModelViewSet):
queryset = models.Assignments.objects.all()
authentication_classes = (TokenAuthentication,)
def get_serializer_class(self):
if self.request.user.is_staff :
print(self.request.user)
return serializers.FullAccessLessonsSerializer
elif self.request.user.is_active:
return serializers.PartialAccessLessonsSerializer
print(self.request.user)
return serializers.BasicAccessLessonsSerializer
My Serializers
Full access for admins:
class FullAccessLessonsSerializer(serializers.ModelSerializer):
class Meta:
model = models.Assignments
fields = ('id', 'title', 'description', 'dllink' )
Basic access for unauthenticated users:
class BasicAccessLessonsSerializer(serializers.ModelSerializer):
class Meta:
model = models.Assignments
fields = ('id', 'title', 'description')
and partial access for students :
class PartialAccessAssignmentsSerializer(serializers.ModelSerializer):
"""A serializer for all Lessons"""
def __init__(self, *args, **kwargs):
fields = kwargs.pop('fields', None)
super(PartialAccessAssignmentsSerializer, self).__init__(*args,**kwargs)
print(self.fields.get('id'))
self.fields.pop('dllink')
class Meta:
model = models.Assignments
fields = ('id','title','description','dllink' )
I have done anything I could found but I can not figure it out. I either an get error or removing all dl links.
dllinkconditionally depending on whether or not the requesting user has already downloaded the Assignments?