Django POST Request nested object primary key

萝らか妹 提交于 2021-01-28 19:38:17

问题


I have a question regarding POST request with nested objects in Django with serializers:

I have checked this:

  • Stackoverflow 1
  • Django Doc
  • Stackoverflow 2

I've created some serializers in my Django project following the architecture below:

EP_project
│
│
└───ep_python
    │   db.sqlite3
    │   manage.py
    │   __init__.py
    │
    ├───ep
    │   │   admin.py
    │   │   apps.py
    │   │   models.py
    │   │   tests.py
    │   │   urls.py
    │   │   __init__.py
    │   │
    │   ├───migrations
    │   │
    │   ├───models
    │   │   │   model_aa.py
    │   │   │   model_ap.py
    │   │   │   model_apr.py
    │   │   │   model_as.py
    │   │   │   model_at.py
    │   │   │   model_b.py
    │   │   │   model_be.py
    │   │   │   model_se.py
    │   │   │   model_s.py
    │   │   │   model_user.py
    │   │   │   __init__.py
    │   │
    │   ├───serializers
    │   │   │   serializers_ap.py
    │   │   │   serializers_user.py
    │   │   │   __init__.py
    │   │
    │   ├───views
    │       │   views_a.py
    │       │   views_user.py
    │
    ├───ep_python
        │   asgi.py
        │   settings.py
        │   urls.py
        │   wsgi.py
        │   __init__.py

Here are my serializers files:

serializers_user.py:

from rest_framework import serializers
from ..models.model_user import User


class UserIndexSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            'first_name',
            'last_name'
        ]

class UserDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

I tried to create a custom create method in my next serializer: serializers_ap.py:

from rest_framework import serializers
from ..models.model_ap import AP
from .serializers_user import *


class APIndexSerializer(serializers.ModelSerializer):
    # user = UserIndexSerializer()

    class Meta:
        model = AP
        fields = [
            'id',
            'user',
            'name'
        ]

    def create(self, validated_data):
        user = User.objects.get(pk=validated_data).id
        # user = User.objects.only('id').get(pk=validated_data)
        # user_id = user["id"]
        # user = User.objects.filter(pk=validated_data).pop("id")
        # instance = Equipment.objects.create(**validated_data)
        ap = AP.objects.create(User=user_id, **validated_data)
        return ap

class APDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = AP
        fields = '__all__'

And here are my views:

views_a.py:

from rest_framework import generics
from ..models.model_ap import AP
from ..serializers.serializers_ap import (
    APIndexSerializer,
    APDetailsSerializer
    )


class APIndex(generics.ListCreateAPIView):
    """List all ap, or create a new ap."""

    queryset = AP.objects.all().order_by('name')
    serializer_class = APIndexSerializer


class APDetails(generics.RetrieveUpdateDestroyAPIView):
    """Retrieve, update or delete an ap instance."""

    queryset = AP.objects.all()
    serializer_class = APDetailsSerializer

views_user.py:

from rest_framework import generics
from ..models.model_user import User
from ..serializers.serializers_user import (
    UserIndexSerializer,
    UserDetailsSerializer
    )


class UserIndex(generics.ListCreateAPIView):
    """List all users, or create a new user."""

    queryset = User.objects.all().order_by('first_name')
    serializer_class = UserIndexSerializer


class UserDetails(generics.RetrieveUpdateDestroyAPIView):
    """Retrieve, update or delete a user instance."""

    queryset = User.objects.all()
    serializer_class = UserDetailsSerializer

The problem is that when I'm posting an AP via postman, it won't get the User ID but only the User object itself. As you can see in my create method in serializers_ap.py, I have tried 3 different ways to extract the ID but with no success.

Postman request:

{
    "user":1,
    "name":"Max AP 01"
}

Postman response:

Field 'id' expected a number but got {'user': <User: Se Po>, 'name': 'Max AP 01'}.

I therefore have 3 questions:

  • Is there something basic I'm missing to get an object's ID?
  • A PUT request providing the User primary key in the request body works fine but not in a POST request, why?
  • To try and make debugging easier I have tried without succes to print variables from the serializer, nothing showed up in Postman response. Is there a way to see them?

Thanks!


回答1:


As I understood, AP model has field

user = models.ForeignKey('User')

If yes, then you can try to change fields in serializer to

fields = [
    'user_id', #or just 'user'
    'name'
]

and then just

ap = AP.objects.create(**validated_data)
return ap


来源:https://stackoverflow.com/questions/60563763/django-post-request-nested-object-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!