我的项目正在使用Django Rest Framework和Djoser。我正在尝试创建一个与用户建立一对一关系的Profile模型,以存储有关用户的额外信息。我的代码如下所示:
settings.py
DJOSER = {
'SERIALIZERS': {
'create_user': 'api.serializers.UserSerializer',
'user': 'api.serializers.UserSerializer'
}
}
serializers.py
from rest_framework import serializers
from django.contrib.auth.models import User
from api.models import *
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('city', 'state', 'zip', 'birth_date', 'user', 'id',)
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login', 'profile',)
models.py
from django.db import models
from django.contrib.auth.models import User, AbstractUser
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
city = models.CharField(max_length=40, blank=False)
state = models.CharField(max_length=2, blank=False)
zip = models.CharField(max_length=5, blank=False)
birth_date = models.DateField(blank=True, null=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
我正在尝试使用Djoser提供的默认路由,当我发布创建用户时,会创建一个配置文件对象,并引用数据库中的User对象。但是,city / state / zip / birth_date实际上并未填充提交的信息。他们只是空白。
以下是我正在使用
进行测试的有效负载的示例{
"username": "test",
"password": "abcdefgh",
"profile": {
"city": "Portland",
"state": "OR",
"zip": "12345"
}
}
无尽的谷歌搜索揭示了我在这里做过的例子。我不知道为什么它不起作用。
HALP。
答案 0 :(得分:0)
settings.py应该是这样的:
DJOSER = {
'SERIALIZERS': {
'user_create': 'api.serializers.UserSerializer',
'user': 'api.serializers.UserSerializer'
}
}