Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How i can to filter queryset by current user in django rest framework

class SalonCarDetailsSerializer(serializers.ModelSerializer):

salon = PrimaryKeyRelatedField(queryset=Salon.objects.filter(owner=?))

class Meta:
    model = SalonCarDetails
    fields = ["salon", "car", "price", "number_of_cars"]

CurrentUserDefault() doesn’t works

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Well, you could write your own PrimaryKeyRelated field like that:

class SalonKeyRelatedField(serializers.PrimaryKeyRelatedField):
    def get_queryset(self):
        qs = super().get_queryset()
        request = self.context.get('request')
        return qs

then you can filter qs by request.user, this will be called only on POST and PUT requests. You can then include it in your serializer

salon = SalonKeyRelatedField()

don’t forget to include salon in your fields

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading