Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-filter

Django - Filter Queryset With Another Modal's Field


I have two modals: Group and GroupContents.

GroupContents Modal:

class GroupContents(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True)
    content= models.TextField(max_length=180)

Group Modal:

class Group(models.Model):
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(blank=True, max_length=80, default='')
    private= models.TextField(blank=False, default='0')

I want to filter my GroupContents queryset as releated Group object not private. I don't know how to solve that. I tried this but didn't work:

class GroupContentsViewSet(viewsets.ModelViewSet):

    serializer_class = GroupContentsSerializer
    authentication_classes = (JSONWebTokenAuthentication,)
    permission_classes = (IsAuthenticatedOrReadOnly,)

    def get_queryset(self):
        queryset = GroupContents.objects.filter(self.group.secret=0)
        return queryset

I don't know how to approach. Thanks a lot...


Solution

  • You can .filter(…) [Django-doc] with:

    class GroupContentsViewSet(viewsets.ModelViewSet):
    
        serializer_class = GroupContentsSerializer
        authentication_classes = (JSONWebTokenAuthentication,)
        permission_classes = (IsAuthenticatedOrReadOnly,)
    
        def get_queryset(self):
            return GroupContents.objects.filter(group__private='0')

    It looks however strange to use a TextField, and not a simple BooleanField [Django-doc].


    Note: normally a Django model is given a singular name, so GroupContent instead of GroupContents.