简体   繁体   中英

How to push data in a model whose one column is a forign key Django Rest Framework?

I'm trying to assign data against specific user using DRF but getting some strange errors. I want your help/ guidance. I'm a beginner but I searched this problem a lot but not able to find any solution.

model.py

class Category(TrackingModels):
    name =models.CharField(default='Learning',max_length=150,unique=True,null=False)
    person=models.ForeignKey(to=User,on_delete=models.CASCADE)
    def __str__(self):
         return self.name

serializer.py

class CategorySerializer(ModelSerializer):
    person = serializers.PrimaryKeyRelatedField(read_only=True)
    class Meta:
        model=Category
        fields=('id','name','person')

views.py

class CategoryAPIView(CreateAPIView):
    serializer_class=CategorySerializer
    permission_classes=(IsAuthenticated,)

    def post(self,request):
        data={
            "person":request.user.id,
            "name":request.data.get('category')
        }
        serializer=CategorySerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response({"message":"Category is created sucessfully!"},status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

Here is Postman request: 在此处输入图像描述

在此处输入图像描述

Asking help here is the only option for me now. I will really appreciate your answers. regards,

I followed this solution but that didn't fixed. I searched a lot on medium and other platforms but all in vein.

You can use the below serializer:

#import 
from django.contrib.auth import get_user_model 
from rest_framework import serializers

UserModel = get_user_model()
class CategorySerializer(ModelSerializer):
    person = serializers.SlugRelatedField(queryset=UserModel.objects.all(), slug_field="id")
    class Meta:
       model=Category
       fields=('id','name','person')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM