Albert
Albert

Reputation: 2664

Querying data with filters using django rest framework

So I'm using django rest framework on top of django as my serverside and MongoDB as a database (a mongo replica set, to be specific).

My model looks like this:

#models.py

class MyModel(models.Model):
    data = models.TextField()

Here's the serializer that I'm using:

#serializers.py

class MySerializer(serializers.ModelSerializer):
    data = serializers.JSONField(binary=True)

    def create(self, validated_data):
        test = MyModel(data=validated_data)
        test.save()
        return test

    class Meta:
        model = MyModel
        fields = ['data']

This is my view:

#views.py

class MyView(APIView):
    serializer_class = MySerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
            serializer.save()
        except djongo.sql2mongo.SQLDecodeError:
            return Response(
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )

        return Response(
            status=status.HTTP_200_OK
        )

Then, in a test mode, I make a few records into the database using httpie. The requests look like this:

http POST localhost:8000/api/test data='{"sizes": ["M", "L"], "colors": ["white", "yellow"], "model": "poet"}'

http POST localhost:8000/api/test data='{"colors": ["red", "black"], "sizes": ["S", "M"], "model": "polo", "material": "silk"}'

http POST localhost:8000/api/test data='{"colors": ["white", "yellow"], "sizes": ["M", "L", "XL"], "model": "poet", "material": "bamboo"}'

The data is written to the DB and replicated. So now I would want to make the following query:

test = MyModel.objects.filter(data__contains={'sizes': ['M', 'L']})

But it returns an empty queryset and it's not supposed to.

What am I doing wrong?

Upvotes: 0

Views: 628

Answers (1)

Lemayzeur
Lemayzeur

Reputation: 8525

According to the Django documentation here:

I think this is what you are looking for (untested)

Model

class MyModel(models.Model):
    data = models.JSONField() # New in Django 1.11.

query

# data='{"sizes": ["M", "L"], "colors": ["white", "yellow"], "model": "poet"}'
MyModel.objects.filter(data__sizes__contains=['M', 'L'])
MyModel.objects.filter(data__model='poet')

Upvotes: 0

Related Questions