I walked through the following documentation at https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/ and tried to use it to learn serialization with DRF.
So, my models.py is:
class Publication(models.Model):
title = models.CharField(max_length=30)
class Meta:
ordering = ('title',)
class Article(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)
class Meta:
ordering = ('headline',)
My serializers.py looks like:
class PublicationSerializer(serializers.ModelSerializer):
class Meta:
model = Publication
fields = ('title',)
class ArticleSerializer(serializers.ModelSerializer):
publications = PublicationSerializer(read_only=True, many=True)
class Meta:
model = Article
fields = ('headline', 'publications')
I created some objects via the shell:
>>> from publications.models import Article, Publication
>>> from publications.serializers import ArticleSerializer, PublicationSerializer
>>> p1 = Publication(title='The Python Journal')
>>> p1.save()
>>> p2 = Publication(title='Science News')
>>> p2.save()
>>> p3 = Publication(title='Science Weekly')
>>> p3.save()
>>> a1 = Article(headline='Django lets you build Web apps easily')
>>> a1.save()
>>> a1.publications.add(p1,p2,p3)
>>> serializer = ArticleSerializer(instance=a1)
>>> serializer.data
{'headline': 'Django lets you build Web apps easily', 'publications': [OrderedDict([('title', 'Science News')]), OrderedDict([('title', 'Science Weekly')]), OrderedDict([('title', 'The Python Journal')])]}
So, when I run the server everything is fine. This the JSON representation when I navigate to /articles:
[
{
"headline": "Django lets you build Web apps easily",
"publications": [
{
"title": "Science News"
},
{
"title": "Science Weekly"
},
{
"title": "The Python Journal"
}
]
}
]
But in my urls.py, I have also a /publications link which shows me the list of publications:
[
{
"title": "Science News"
},
{
"title": "Science Weekly"
},
{
"title": "The Python Journal"
}
]
So, the first JSON representation (/articles) shown above which shows me the articles gives me a list of publications related to the article. As I said before, this looks as expected. But in the 2nd JSON representation (/publications) which shows me the list of publications I can not see a list of articles related to each publication. How can I do that ? Should I add another ManyToManyField to Publication class ? Or is a ForeignKey field enough ? What I want is a JSON representation like the following when I navigate to /publications:
[
{
"title": "Science News"
"article":[ <-- This info should be added
"..." , etc.
]
},
{
"title": "Science Weekly"
"article":[
"..." , etc.
]
},
{
"title": "The Python Journal"
"article":[
"..." , etc.
]
}
]
I hope somebody can help. Thanks in advance :)
You don't need to add any model fields. You just need to add "article_set" to the fields
list in PublicationSerializer.