gpt4 book ai didi

python - Django Rest Framework - 发布外键

转载 作者:太空宇宙 更新时间:2023-11-03 14:00:12 26 4
gpt4 key购买 nike

我是 Django Rest Framework 的新手,查看了一些教程。现在我正在尝试创建自己的结构,如下所示。我想创建一个可以的用户,然后单独创建一个配置文件。

模型.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

序列化器.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)

我要发布的数据

{
"user_id": {
"id": 2
},
"email": "xxx@gmail.com",
"birthday": "1991-05-28",
"bio": "qudur",
"points": 31
}

我得到的错误;

NOT NULL constraint failed: core_profile.user_id

我哪里做错了?谢谢!

最佳答案

您的 ProfileSerializeruser 设置为 readonly。所以你需要改变它。我建议这样做

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)

如果你这样做,你可以提供你的 user 作为 POST 的普通 id

{
"user": 2,
"email": "xxx@gmail.com",
"birthday": "1991-05-28",
"bio": "qudur",
"points": 31
}

当你读取数据时,它看起来像这样

{
"user": {
"id": 2,
"name": "Name",
"surname": "Surname",
...
},
"email": "xxx@gmail.com",
"birthday": "1991-05-28",
"bio": "qudur",
"points": 31
}

关于python - Django Rest Framework - 发布外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50256852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com