在DRF的串行器和模型设计之间进行转换

时间:2015-02-01 12:51:17

标签: django django-rest-framework

我正在使用Django Rest Framework来支持在我的Web应用程序的前端使用Annotator.JS(http://annotatorjs.org/)。问题是我用来存储用户所做的任何注释的模型与Annotator.JS在AJAX请求中从前端发送的JSON不同。

Annotator.JS'JSON的结构是:

{
  "id": "39fc339cf058bd22176771b3e3187329",  # unique id (added by backend)
  "annotator_schema_version": "v1.0",        # schema version: default v1.0
  "created": "2011-05-24T18:52:08.036814",   # created datetime in iso8601 format (added by backend)
  "updated": "2011-05-26T12:17:05.012544",   # updated datetime in iso8601 format (added by backend)
  "text": "A note I wrote",                  # content of annotation
  "quote": "the text that was annotated",    # the annotated text (added by frontend)
  "uri": "http://example.com",               # URI of annotated document (added by frontend)
  "ranges": [                                # list of ranges covered by annotation (usually only one entry)
    {
      "start": "/p[69]/span/span",           # (relative) XPath to start element
      "end": "/p[70]/span/span",             # (relative) XPath to end element
      "startOffset": 0,                      # character offset within start element
      "endOffset": 120                       # character offset within end element
    }
  ],
  "user": "alice",                           # user id of annotation owner (can also be an object with an 'id' property)
  "consumer": "annotateit",                  # consumer key of backend
  "tags": [ "review", "error" ],             # list of tags (from Tags plugin)
}

我的Annotation模型的结构是:

class Annotation(models.Model):
    datapoint = models.ForeignKey('datapoint.Datapoint', related_name='%(class)s_parent_datapoint_relation')
    owner = models.ForeignKey('users.User', related_name='%(class)s_creator_relation')

    # Key fields from the Annotator JSON Format: http://docs.annotatorjs.org/en/latest/annotation-format.html
    annotator_schema_version = models.CharField(max_length=8, blank=True)
    text = models.TextField(blank=True)
    quote = models.TextField()
    uri = models.URLField(blank=True)
    range_start = models.CharField(max_length=50, blank=True)
    range_end = models.CharField(max_length=50, blank=True)
    range_startOffset = models.BigIntegerField()
    range_endOffset = models.BigIntegerField()
    tags = TaggableManager(blank=True)

如何创建可以从模型结构转换为JSON的序列化程序?

P.S。 Annotator.JS允许用户使用上面提到的JSON结构发送额外信息,因此Datacoint不包含在JSON结构中这一事实不是问题。这可以毫无问题地传递。希望所有者在JSON中与User相等。

感谢您的帮助,非常感谢。

1 个答案:

答案 0 :(得分:0)

只需使用默认的ModelSerializer,您就可以免费为所有简单字段(版本,文本,引用,uri)进行序列化,只需指定要序列化的字段即可。其他领域也很简单:

  • 要组成范围对象,可以使用SerializerMethodField,它允许您定义自定义序列化程序方法(返回包含模型中range_ *属性值的字典数组)。请注意,如果您还需要能够将JSON反序列化到模型中,则需要定义自定义字段。
  • 来自所有者 - > user_id SlugRelatedField(假设您可以从User对象访问所需的用户ID)
  • 你也可以使用SlugRelatedField从TaggableManager转发 - > [" tag"," values"](再次假设您可以通过TaggableManager管理的模型对象访问您想要的值。

一般而言,文档中会详细描述您想要的所有内容。