基于JSONField嵌套对象的Django-Rest框架过滤器

2024-09-30 20:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python(3)、Django(1.11)和DRF开发一个项目,在这个项目中,我必须基于在db模型中保存为JSONFIELDjson对象字段来过滤数据。在

以下是我尝试过的:

# 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 the MyModel objects where the props ID by the GET request at /mymodel/props/<ID>. If the requested props 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过滤对象呢?在

请帮帮我! 提前谢谢!在


Tags: theidjsonobjectmodelsbepropsat
2条回答

您正在寻找的功能是可能的,但不幸的是它不是那么简单。据我所知,jsonfield包不支持它,但是您必须使用Postgres as your database backend and use its internal JSONField。我想你可以选择以下一种:

  • 切换到django.contrib.postgres.fields.JSONField并在所有环境中使用Postgres作为您的数据库后端(然后支持这样的查找)
  • 使数据遵循特定模式,并将JSONField更改为单独的模型和表
  • 使用混合存储解决方案和JSON文档专用解决方案
  • 将需要查询的字段提取到模型中-启用查询,但将非结构化数据保留在JSONField中。在
class MyModel(models.Model):
    id = models.CharField(primary_key=True, max_length=255)
    type = models.CharField(max_length=255)
    props = jsonfield.JSONField()
    props_id = models.IntegerField(null=True)
    repo = jsonfield.JSONField()
    repo_id = models.IntegerField(null=True)
    created_at = models.DateTimeField()

然后手动或在模型的save()中设置id值:

^{pr2}$

你应该用

from django.contrib.postgres.fields import JSONField

而不是

^{pr2}$

在那之后,我认为一切都应该正常运转

相关问题 更多 >