所以我在django上使用django rest框架作为我的服务器端,使用MongoDB作为数据库(mongo副本集,具体而言)。
我的模型看起来像这样:
class MyModel(models.Model):
data = models.TextField()
这是我使用的序列化程序:
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']
这是我的观点:
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
)
然后,在测试模式下,我使用httpie在数据库中创建了一些记录。请求看起来像这样:
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"}'
将数据写入数据库并进行复制。所以现在我想做出以下查询:
test = MyModel.objects.filter(data__contains={'sizes': ['M', 'L']})
但是它返回一个空的查询集,它不应该。
我做错了什么?
答案 0 :(得分:1)
根据Django文档here:
我认为这就是你要找的(未经测试)
模型
class MyModel(models.Model):
data = models.JSONField() # New in Django 1.11.
查询
# data='{"sizes": ["M", "L"], "colors": ["white", "yellow"], "model": "poet"}'
MyModel.objects.filter(data__sizes__contains=['M', 'L'])
MyModel.objects.filter(data__model='poet')