Django:使用直通参数序列化具有多对多关系的模型 [英] Django: Serialize a model with a many-to-many relationship with a through argument

查看:71
本文介绍了Django:使用直通参数序列化具有多对多关系的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该模型定义了一个文章和一个作者类.它们以多对多的关系连接在一起.这种关系是通过自定义中间表定义的:

The model defines an Article and an Author classes. They are linked together with a many-to-many relationship. This relationship is defined through an custom intermediary table:

# 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:

The serialization should return a JSON like this:

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

我确定了两种解决方案.

I've identified two solutions.

  • This one suggests to serialize the AuthorOrder field separately.
  • The second one is to use the Django Rest Framework.

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

I tried the twos but without success. Do you know another way to do it?

推荐答案

感谢您的反馈,我专注于 Django REST 框架并且它有效.以下是我编写的自定义序列化程序:

Thanks to your feedback, I focused on Django REST framework and it works. Here are the custom serializers I've written:

# 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 ArticleSerializer(serializer.ModelSerializer):
    authors = AuthorsOrderSerializer(source='authorsorder_set', many=True)

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

来源:

  1. 在响应中包含中介(通过模型)Django Rest 框架
  2. https://bitbucket.org/snippets/adautoserpa/MeLa/django-rest-framework-manytomany-through

这篇关于Django:使用直通参数序列化具有多对多关系的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆