1

I have below model in my models.py which has the django User model as the foreign key and I want to add username into the filterset_fields in my views in order to filter the user employment by username instead of user id. Any help would be great! Thank you!

class UserEmployment(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='employment')
    position = models.TextField(blank=True)
    company = models.TextField(blank=True)
    start_year = models.IntegerField(blank=True, null=True)
    end_year = models.IntegerField(blank=True, null=True)
    currently_work = models.BooleanField(default=False)

Serializer class,

class UserEmploymentSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserEmployment
        fields = ['id', 'user', 'position', 'company', 'start_year', 'end_year', 'currently_work']

View class,

class UserEmploymentViewSet(viewsets.ModelViewSet):

    queryset = UserEmployment.objects.all()
    serializer_class = UserEmploymentSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['user'] # I want this to be 'username' in order to filter employment list by username
    http_method_names = ['get']

Thank you!

2 Answers 2

3

You can use filterset_class attr.

from django_filters import rest_framework
class UserEmploymentFilter(rest_framework.FilterSet):
    username = rest_framework.CharFilter(field_name='user__username', lookup_expr='iexact')

    class Meta:
        fields = ("username",)
        model = UserEmployment
    

And your view should be like this

class UserEmploymentViewSet(viewsets.ModelViewSet):

    queryset = UserEmployment.objects.all()
    serializer_class = UserEmploymentSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = UserEmploymentFilter
    http_method_names = ['get']

After that you can search with ?username=foo

3
  • Thank you very much. It worked! I also tried overriding get_queryset() method and it also works fine. Which way is better as you think? Commented Dec 1, 2020 at 13:26
  • 1
    In my opinion, filterset-class is better than override queryset since your view won't swell up Commented Dec 1, 2020 at 14:25
  • Yeah! Thanks a lot again! Commented Dec 1, 2020 at 15:18
-1

This also works fine,

class UserEmploymentViewSet(viewsets.ModelViewSet):

    queryset = UserEmployment.objects.all()
    serializer_class = UserEmploymentSerializer
    filter_backends = [DjangoFilterBackend]
    http_method_names = ['get']

    def get_queryset(self):
    
        queryset = UserEmployment.objects.all()
        username = self.request.query_params.get('username', None)
        if username is not None:
            queryset = queryset.filter(user__username=username)
        return queryset

Reference: https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.