我正在使用Python(3)、Django(1.11)和DRF开发一个项目,在这个项目中,我必须基于在db模型中保存为JSONFIELD
的json
对象字段来过滤数据。在
以下是我尝试过的:
# 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()
^{pr2}$
# 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
It should return the MyModel records by
props ID
and should be able to return the JSON array of all theMyModel objects
where theprops ID
by the GET request at/mymodel/props/<ID>
. If the requestedprops
does not exist then HTTP response code should be 404, otherwise, the response code should be 200. The JSON array should be sorted in ascending order by MyModel ID.
当我向该视图发送请求时,它返回一个错误:
> 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
过滤对象呢?在
请帮帮我! 提前谢谢!在
您正在寻找的功能是可能的,但不幸的是它不是那么简单。据我所知,
jsonfield
包不支持它,但是您必须使用Postgres as your database backend and use its internal JSONField。我想你可以选择以下一种:django.contrib.postgres.fields.JSONField
并在所有环境中使用Postgres作为您的数据库后端(然后支持这样的查找)然后手动或在模型的
^{pr2}$save()
中设置id值:你应该用
而不是
^{pr2}$在那之后,我认为一切都应该正常运转
相关问题 更多 >
编程相关推荐