[Django]-Django: Serialize a model with a many-to-many relationship with a through argument

39👍

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')

Sources:

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

Leave a comment