Django:使用through参数序列化具有多对多关系的模型

时间:2017-02-01 10:01:32

标签: django serialization

该模型定义了Article和Author类。它们以多对多的关系联系在一起。此关系通过自定义中间表定义:

# models.py
class Article(models.Model):
    title = models.CharField(max_length=500)
    authors = models.ManyToManyField(Author, through='AuthorOrder')

class Author(models.Model):
    name = models.CharField(max_length=255)

class AuthorOrder(models.Model):
    author = models.ForeignKey(Author)
    article = models.ForeignKey(Article)
    writing_order = models.IntegerField()

序列化应返回如下的JSON:

#articles_json
{"fields":
     {
         "title": "A title",
         "authors": [
             {
                 "name":"Author 1",
                 "writing_order": 1
             },
             {
                 "name":"Author 2",
                 "writing_order": 2
             }
         }
     }
}

我发现了两种解决方案。

我尝试了两次但没有成功。你知道另一种方法吗?

1 个答案:

答案 0 :(得分:3)

感谢您的反馈,我专注于Django REST框架,它的工作原理。以下是我编写的自定义序列化器:

# serializers.py
from rest_framework import serializers
from app.models import Article, AuthorsOrder


class AuthorsOrderSerializer(serializer.ModelSerializer):
    author_name = serializers.ReadOnlyField(source='author.name')

    class Meta:
        model = AuthorsOrder
        fields = ('writing_order', 'author_name')


class AuthorsOrderSerializer(serializer.ModelSerializer):
    authors = AuthorsOrderSerializer(source='authorsorder_set', many=True)

    class Meta:
        model = Article
        fields = ('title', 'authors')

来源:

  1. Include intermediary (through model) in responses in Django Rest Framework
  2. https://bitbucket.org/snippets/adautoserpa/MeLa/django-rest-framework-manytomany-through