Django Rest compare user id 'sector' id with publication 'sector' id

1

Well, I'm messing with an API and I want it to return the content only when the user sector is the same as the publishing sector.

Publications API:

The user has a sector field also equal to this, and I am already getting the id of the sector of the current user, but I can not get the sector id of the publication to test!

views.py

class PostDetailAPIView(RetrieveAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer

def get_queryset(self):
    queryset = Post.objects.all()
    user_sector = None
    if self.request.user.is_authenticated():
        user_sector = self.request.user.sector.id

        if user_sector is ...:
            return queryset

remembering that I want to return to queryset whenever the sector of some publication is equal to the sector of the logged in user !! help me on this

    
asked by anonymous 11.09.2017 / 02:57

2 answers

0

Well, I found the solution in a different way, I made a filter on the objects by the sector id, and it looked like this:

ps: I also put an OR condition to search for the 'General' sector, which should appear for all users

from django.db.models import Q 

class PostListAPIView(ListAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer

def get_queryset(self):
    user_sector = None
    if self.request.user.is_authenticated():
        user_sector = self.request.user.sector.id
        queryset = Post.objects.filter(
                        Q(sector__id=user_sector) |
                        Q(sector__name='Geral')
                        ).distinct()   
        return queryset
    
16.09.2017 / 19:41
0

There's more to a permission issue, so I understand. So when the publishing sector is different from the user sector you want to decline that request (and probably return an error message).

I would implement it as follows:

class PostDetailAPIView(RetrieveAPIView):
 queryset = Post.objects.all()
 serializer_class = PostSerializer
 permission_classes = (ClasseVerificacao)

Then you need to implement the " Verification Class "

# CLASSES PARA CONTROLE DE PERMISSIONS
class ClasseVerificacao(permissions.BasePermission):
  message = 'Permissão negada, seu setor não é o mesmo do objeto'

  def has_object_permission(self, request, view, obj):
    return self.request.user.sector == obj.sector

Notice that this part returns True when the user sector is equal to the sector of the object. When the function returns True it responds to the request, if the function returns False it responds to the request with the message you have chosen.

  

return self.request.user.sector == obj.sector

Well it's "complicated" to make the code exactly for your problem, there is an example that should help you. And remember to look at the documentation.

    
12.09.2017 / 02:45