Submitting foreign key relationships in Django Rest Framework

In my models , I have the following classes:

class Topic(models.Model):
    name = models.CharField(max_length=25, unique=True)

class Content(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    topic = models.ForeignKey(Topic, blank=True, null=True)

My serializers look like this:

class TopicSerializer(serializers.ModelSerializer):
     class Meta:
         model = Topic
         fields = ('name')

class ContentSerializer(serializers.ModelSerializer):
     topic = TopicSerializer(read_only=True)
     class Meta:
          model = Content
          fields = ('title', 'body', 'topic')

Ok, so in my urls file I have the following template:

urlpatterns = [
    ...
    url(r'^api/topic_detail/(?P<name>[a-zA-Z0-9-]+)/content_list/$', views.topic_content_list, name='topic_content_list'),
    ...
]

Therefore, when the user navigates to /api/topic_detail/sports/content_list/, we get a list of all the content in which there is a sports theme . Now I want POST to display the following data at the above URL, then a Content object is created with a subject field that is automatically associated with the sport.

I am trying to do this as follows in the views :

@api_view(['GET', 'POST'])
def topic_content_list(request, name):
    try:
        topic = Topic.objects.get(name=name)
    except:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        contents = Content.objects.filter(topic=topic)
        serializer = ContentSerializer(contents, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        request.data["topic"] = topic
        serializer = ContentSerializer(data=request.data)
        print request.data
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Now let's say that I go URL /api/topic_detail/sports/content_list/and POST:

{
    "title": "My blog post",
    "body" : ".....",
}

, . null. ? .

, , , , .

, :

class ContentSerializer(serializers.ModelSerializer):
     topic = TopicSerializer(read_only=False)
     class Meta:
          model = Content
          fields = ('title', 'body', 'topic')

, read_only False. :

{
    "topic": {
        "non_field_errors": [
            "Invalid data. Expected a dictionary, but got Topic."
        ]
    }
}

, , , data.website, , JSON, Django. JSONify ?

+4
1

.

     topic = TopicSerializer(read_only=True)

, , , . , .

:

, , , dict, , . .

topic_dict = { "name": topic.name }

"" ​​ request.data, topic_id, , .

- :

request.data["topic_id"] = topic.id

, , .

+5

Source: https://habr.com/ru/post/1651567/


All Articles