在Django中创建父对象时如何同时创建相关的一对一对象?

z2acfund  于 2023-05-01  发布在  Go
关注(0)|答案(1)|浏览(123)

我有一个User模型,它在一个名为 core 的应用程序中扩展了AbstractUser模型。我在 * 设置中将此模型用作AUTH_USER_MODEL。py*.我还有一个UserProfile模型,它与User有一对一的关系。我的目标是,每当同时创建一个新用户时,都要创建一个UserProfile。

# file name: core/models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    email = models.EmailField(unique=True)
    

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)

**问题:**当我使用shell创建一个新用户时,我得到这个错误:

>>> bob = User.objects.create_user(email="bob@outlook.com", username="bob")

TypeError: int() argument must be a string, a bytes-like object or a real number, not 'ModelBase'
The above exception was the direct cause of the following exception:

TypeError: Field 'id' expected a number but got <class 'core.models.User'>.

During handling of the above exception, another exception occurred:

ValueError: Cannot assign "<class 'core.models.User'>": "UserProfile.user" must be a "User" instance.
>>>

我应该如何解决这个错误?
为了在每次创建新的User时创建UserProfile,我使用如下所示的信号:

# file name: core/signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from core.models import User, UserProfile

@receiver(post_save, sender=User)
def create_userprofile(sender, **kwargs):
    try:
        UserProfile.objects.get(user=sender)
    except Exception:
        sender.userprofile = UserProfile.objects.create(user=sender)

我已经在app config类中注册了这个信号:

# file name: core/apps.py

from django.apps import AppConfig

class CoreConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'core'
    
    def ready(self):
        from . import signals
        
        return super().ready()
uyto3xhc

uyto3xhc1#

使用上面的方法可能不会以您预期的方式工作,因为您没有添加:

User = settings.AUTH_USER_MODEL

create_user_profile函数中缺少instancecreated
signals.py文件应该是:

from django.conf import settings 
from django.db.models.signals import post_save 
from django.dispatch import receiver 
from core.models import UserProfile
  
User = settings.AUTH_USER_MODEL

@receiver(post_save, sender=User) 
 def create_user_profile(sender, instance, created, **kwargs): 
     if created: 
         UserProfe.objects.create(user=instance)

相关问题