我正在使用 Python(3)、Django(1.11) 和 DRF 开发一个项目,在该项目中,我必须根据json
保存为JSONFIELD
db 模型的对象字段过滤数据。
这是我尝试过的:
# model.py
from django.db import models
import jsonfield
class MyModel(models.Model):
id = models.CharField(primary_key=True, max_length=255)
type = models.CharField(max_length=255)
props = jsonfield.JSONField()
repo = jsonfield.JSONField()
created_at = models.DateTimeField()
# serializers.py
class MyModelSerializer(serializers.ModelSerializer):
props = serializers.JSONField()
repo = serializers.JSONField()
class Meta:
model = EventModel
fields = "__all__"
# JSON object
{
"id":4633249595,
"type":"PushEvent",
"props":{
"id":4276597,
"login":"iholloway",
"avatar_url":"https://avatars.com/4276597"
},
"repo":{
"id":269910,
"name":"iholloway/aperiam-consectetur",
"url":"https://github.com/iholloway/aperiam-consectetur"
},
"created_at":"2016-04-18 00:13:31"
}
# views.py
class PropsEvents(generics.RetrieveAPIView):
serializer_class = MyModelSerializer
def get_object(self):
print(self.request.parser_context['kwargs']['id'])
queryset = MyModel.objects.filter(data__props__id=self.request.parser_context['kwargs']['id'])
obj = get_object_or_404(queryset)
return obj
它应该返回 MyModel 记录,
props ID
并且应该能够通过 GET 请求返回所有MyModel objects
位置的 JSON 数组。如果请求的不存在,则 HTTP 响应代码应为 404,否则,响应代码应为 200。 JSON 数组应按 MyModel ID 升序排序。props ID
/mymodel/props/<ID>
props
当我向这个视图发送请求时,它返回一个错误:
> django.core.exceptions.FieldError: Unsupported lookup 'id' for JSONField or join on the field not permitted.
> [18/Feb/2019 10:37:39] "GET /events/actors/2790311/ HTTP/1.1" 500 16210
那么,如何根据 ? 过滤对象id of props
?
请帮帮我!提前致谢!