Answer the question
In order to leave comments, you need to log in
How to generate json in serializers.ModelSerializer?
I am using django rest framework. Here are two models:
class ArticleList(models.Model):
name = models.CharField(
max_length=120,
blank=False,
null=False,
unique=True,
verbose_name='Название'
)
reverse = models.BooleanField(
default=False,
blank=False,
null=False,
verbose_name='Обратный'
)
class Article(models.Model):
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
null=False,
verbose_name='Пользователь',
default=2
)
article= models.ForeignKey(
ArticleList,
on_delete=models.PROTECT,
null=False,
)
repeat = models.IntegerField(
blank=False,
null=False,
verbose_name='Повтор'
)
date = models.DateTimeField(
blank=False,
null=False,
verbose_name='Дата и время'
)
class ArticleListSerializer(serializers.ModelSerializer):
class Meta:
model = ArticleList
fields = ('name', 'reverse')
class ArticleSerializer(serializers.ModelSerializer):
article= ArticleListSerializer()
class Meta:
model = Article
fields = ('repeat', 'date', 'article')
[
{
"repeat": 8,
"date": "2019-04-01T08:25:00+03:00",
"article": {
"name": "Имя 1",
"reverse": true
}
},
{
"repeat": 10,
"date": "2019-04-01T08:28:00+03:00",
"article": {
"name": "Имя 1",
"reverse": true
}
},
{
"repeat": 10,
"date": "2019-04-01T08:31:00+03:00",
"article": {
"name": "Имя 1",
"reverse": true
}
}
]
{
"name":"Имя 1",
"reverse":true,
"article":[
{
"repeat":8,
"date":"2019-04-01T08:25:00+03:00"
},
{
"repeat":10,
"date":"2019-04-01T08:28:00+03:00"
},
{
"repeat":10,
"date":"2019-04-01T08:31:00+03:00"
}
]
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question