V
V
vagitaku2019-06-01 00:47:34
Django
vagitaku, 2019-06-01 00:47:34

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='Дата и время'
    )

So I serialize:
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')

I get this json:
[
    {
        "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
        }
    }
]

You can do something in the serealizer so that json is of this format:
{  
   "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 question

Ask a Question

731 491 924 answers to any question