Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

python - Django Rest Framework - Post Foreign Key

I am new to Django Rest Framework and checked some tutorials. Now I am trying to create my own structure which is like following. I want to create a user which is OK, then create a profile seperately.

models.py

class User(models.Model):

  name = models.CharField(max_length=32)
  surname = models.CharField(max_length=32)
  facebook_id = models.TextField(null=True)
  is_sms_verified = models.BooleanField(default=False)
  created = models.DateTimeField(default=timezone.now)
  updated = models.DateTimeField(default=timezone.now)
  status = models.BooleanField(default=1)

 def __str__(self):
  return self.name+" "+self.surname

class Profile(models.Model):

  user = models.ForeignKey('User',on_delete=models.CASCADE)
  email = models.CharField(max_length=32)
  birthday = models.DateField(null=True)
  bio = models.TextField(null=True)
  points = models.IntegerField(default=0)
  created = models.DateTimeField(default=timezone.now)
  updated = models.DateTimeField(default=timezone.now)

  def __str__(self):
   return self.user.name+ " " + self.user.surname

serializers.py

class UserSerializer(serializers.ModelSerializer):

  class Meta:
    model=User
    fields = ('id','name','surname','facebook_id','is_sms_verified',)
    read_only_fields = ('created','updated')

class ProfileSerializer(serializers.ModelSerializer):
  user = UserSerializer(read_only=True)

  class Meta:
    model=Profile
    fields=('id','user','email','birthday','bio','points')
    read_only_fields = ('created','updated')

views.py

@api_view(['POST'])
def profile_create(request):
  serializer = ProfileSerializer(data=request.data)
  if serializer.is_valid():
    serializer.save()
    return JsonResponse(serializer.data, status = status.HTTP_201_CREATED)
  return JsonResponse(serializer.errors , status= status.HTTP_400_BAD_REQUEST)

data I'm trying to post

{
  "user_id": {
      "id": 2
   },
  "email": "[email protected]",
  "birthday": "1991-05-28",
  "bio": "qudur",
  "points": 31
}

The error I get;

NOT NULL constraint failed: core_profile.user_id

Where am I doing wrong? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your ProfileSerializer has user as readonly. So you need to change that. I would suggest doing it like this

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model=Profile
        fields=('id','user','email','birthday','gender','bio','points')
        read_only_fields = ('created','updated')

    def to_representation(self, instance):
        self.fields['user'] =  UserSerializer(read_only=True)
        return super(ProfileSerializer, self).to_representation(instance)

If you do it this you could provide your user as plain id for POST

{
  "user": 2,
  "email": "[email protected]",
  "birthday": "1991-05-28",
  "bio": "qudur",
  "points": 31
}

And when you will read data it will look like this

{
  "user": {
    "id": 2,
    "name": "Name",
    "surname": "Surname",
    ...
  },
  "email": "[email protected]",
  "birthday": "1991-05-28",
  "bio": "qudur",
  "points": 31
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...