I
I
Ilya Trusov2018-03-01 19:10:28
Django
Ilya Trusov, 2018-03-01 19:10:28

How to serialize ForeignKey in django rest?

Hello, I'm using the latest djnago rest framework.
There is such a model:

class Subscriptions(models.Model):
    """Подписки. Привязка подписчиков к подписным листам"""

    subs_list = models.ForeignKey(SubsList, verbose_name='Subscription list', on_delete=models.CASCADE,  related_name='subs_list')  # идентификатор подписного листа
    subscriber = models.ForeignKey(Subscribers, verbose_name='Subscriber', on_delete=models.CASCADE)  # идентификатор подписчика
    created_date = models.DateTimeField(verbose_name='Created date', auto_now=True)  # дата добавления подписчика в подписной лист
    deleted = models.NullBooleanField(verbose_name='Deleted')  # True-удален из подписного листа, False/null-в подписном листе

How can I serialize it? The main question is how to serialize a ForeignKey so that the related data is returned when requested, i.e. NOT:
"id": 29,
      "created_date": "2018-03-01T14:28:41.237742Z",
      "deleted": false,
      "subs_list": 1,
      "subscriber": 1

and like this:
"id": 29,
      "subs_list": {
        "id": 1,
        "uuid": "d183bab7-af26-48f8-9ef5-ea48e09a95a9",
        "name": "TEST",
        "description": "TEST",
        "created_date": "2018-03-01T13:15:18.808709Z",
        "deleted": null,
        "user": 6
      },
      "subscriber": {
        "id": 1,
        "bot_id": "1",
        "name_messenger": "11",
        "username": "1",
        "first_name": "1",
        "last_name": "1",
        "created_date": "9999-03-01T16:47:51.440000Z",
        "subscribed": true,
        "chat_bot": "1",
        "phone": "1",
        "user": 1
      },
      "created_date": "2018-03-01T14:28:41.237742Z",
      "deleted": false

I have this serializer:
from rest_framework import serializers
from subscriptions.models.subscribers import Subscriptions
from subscriptions.serializers.subs_list import SubsListSerializer
from subscriptions.serializers.subscribers import SubscribersSerializer


class SubscriptionsSerializer(serializers.ModelSerializer):
    subs_list = SubsListSerializer(read_only=True)
    subscriber = SubscribersSerializer(read_only=True)

    class Meta:
        model = Subscriptions
        fields = '__all__'

With get requests, everything is ok, but how to update and add data is not clear, the error is:
IntegrityError at /subscriptions/subscriptions/
null value in column "subs_list_id" violates not-null constraint
DETAIL:  Failing row contains (41, 2018-03-01 16:10:02.383625+00, f, null, null).

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