我更喜欢使用 django信号模块,它在发生某些事情时向应用程序发送信号,除此之外,您还可以在其他函数之前/之后调用自己的函数。我的回答类似于 Stuart 的回答,但将所有与您的新扩展类相关的代码保存在一个地方(如果您想稍后删除配置文件或更改其名称,您不必查看其他任何地方)。
以下代码列出了您的扩展类模型,在本例中为用户配置文件,然后在创建用户模型时创建一个空实例,然后通过保存父用户实例来保存具有新信息(您必须自己添加)的实例,即-user.save()
模型.py
from django.db.models.signals import post_save
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model): #This extends the user class to add profile information
user = models.OneToOneField(User, on_delete=models.CASCADE)
#add your extra traits here: is_nice, is_shwifty, address, etc.
is_nice = models.BooleanField(default=True, blank=True)
# a user model was just created! This now creates your extended user (a profile):
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
# instance is the user model being saved.
Profile.objects.create(user=instance)
# a user model was just saved! This now saves your extended user (a profile):
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
如果您没有 ProfileSerializer:serializers.py
#use hyperlinkedmodelserializer for easy api browsing + clicking
class ProfileSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer()
class Meta:
model = Profile
fields = ('url', 'user', 'is_nice')
创建用户并保存用户后,您将拥有一个空的 user.profile 来添加信息。例如,运行python manage.py shell
try 后:
from backend.models import User, Profile
#create your user
user=User(username="GravyBoat")
user.save()
#now update your user's profile
user.profile.is_nice=False
#that's one mean gravy boat
user.save()
user.profile.is_nice
#False