ValueError:无法分配对象用户必须是“ User”实例

时间:2018-10-30 00:12:19

标签: python django django-models

这对我来说很奇怪。我正在Django信号接收器create_customer_settings内设置一个断点来调试它。即使成功创建了新的ValueError对象,应用程序也会抛出CustomerSettings。当我尝试第二次创建它时,出现了UNIQUE约束错误,但这是因为已成功添加它。

为什么ValueErrorisinstance(this_user, User) == True

这是我可以安全捕获并忽略的错误吗?是因为CustomerSettings ID与User ID不同而引起的问题吗?

create_customer_settings

@receiver(post_save, sender=User)
def create_customer_settings(sender, instance, created, **kwargs):
    if created:
      this_user = User.objects.get(id=instance.id)
      pdb.set_trace()
      CustomerSettings.objects.create(
          user=this_user, 
          email=this_user.email, 
          date_of_birth="1998-01-04", 
          in_private_mode=False
    )                                 

pdb.set_trace()输出1:

System check identified no issues (0 silenced).
October 29, 2018 - 23:42:57
Django version 2.1.1, using settings 'myapp.settings'
Starting development server at http://127.0.0.1:7000/
Quit the server with CONTROL-C.
> /src/myapp/myapp/models.py(36)create_customer_settings()
-> pdb.set_trace()
(Pdb) this_user
<User: new_user_8080>
(Pdb) isinstance(this_user, User)
True
(Pdb) CustomerSettings.objects.create(
    user=this_user, 
    email=this_user.email, 
    date_of_birth="1998-01-04", 
    in_private_mode=False
)                                 
*** ValueError: Cannot assign 
"<CustomerSettings: CustomerSettings object (6)>": 
"CustomerSettings.user" must be a "User" instance.

pdb.set_trace()输出2:

(Pdb) this_user.is_anonymous
False
(Pdb) this_user
<User: new_user_8080>
(Pdb) CustomerSettings.objects.create(
    user=this_user, 
    email=this_user.email, 
    date_of_birth="1998-01-04", 
    in_private_mode=False
)                                 
*** django.db.utils.IntegrityError: 
UNIQUE constraint failed: myapp_customersettings.user_id
(Pdb) CustomerSettings.objects.all()
<QuerySet [<CustomerSettings: CustomerSettings object (1)>,
<CustomerSettings: CustomerSettings object (2)>,
<CustomerSettings: CustomerSettings object (3)>,
<CustomerSettings: CustomerSettings object (4)>,
<CustomerSettings: CustomerSettings object (5)>,
<CustomerSettings: CustomerSettings object (6)>]>
(Pdb) CustomerSettings.objects.all().values()
<QuerySet [
{'id': 1, 'user_id': 1, 'timezone': 'America/New_York', 'email':...
    ...
    ...
    ... 
, {'id': 6, 'user_id': 15, 'timezone': '', 'email': 'new_user_8080@gmail.com', 
'email_confirmed': False, 'date_of_birth': datetime.date(1998, 1, 4), 'first_name': '', 'last_name': '', 'in_private_mode': False}]>
(Pdb) CustomerSettings.objects.filter(user_id=15)
<QuerySet [<CustomerSettings: CustomerSettings object (6)>]>
(Pdb) CustomerSettings.objects.filter(user_id=15).values()
<QuerySet [{'id': 6, 'user_id': 15, 'timezone': '', 'email': 'new_user_8080@gmail.com', 'email_confirmed': False, 'date_of_birth': datetime.date(1998, 1, 4), 'first_name': '', 'last_name': '', 'in_private_mode': False}]>
(Pdb) CustomerSettings.objects.filter(user_id=15).values()[0]
{'id': 6, 'user_id': 15, 'timezone': '', 'email': 'new_user_8080@gmail.com', 'email_confirmed': False, 'date_of_birth': datetime.date(1998, 1, 4), 'first_name': '', 'last_name': '', 'in_private_mode': False}
(Pdb) CustomerSettings.objects.filter(user_id=15).values()[0]['id']
6
(Pdb) User.objects.get(id=15)
<User: new_user_8080>
(Pdb) 

CustomerSettings型号:

class CustomerSettings(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, null=False, blank=False)
    timezone = models.CharField(max_length=50, choices=TIMEZONE_CHOICES, blank=False, null=False)
    email = models.EmailField(
            verbose_name='email address',
            max_length=255, blank=False, null=False,
            unique=True)
    email_confirmed = models.BooleanField(default=False)
    date_of_birth = models.DateField()
    first_name = models.CharField(max_length=50, null=False, blank=False)
    last_name = models.CharField(max_length=50, null=False, blank=False)
    in_private_mode = models.BooleanField()

2 个答案:

答案 0 :(得分:1)

再次检查您发布的代码是否正在运行。错误消息ValueError: Cannot assign "<CustomerSettings: CustomerSettings object (6)>": "CustomerSettings.user" must be a "User" instance表示您正在尝试创建CustomerSettings属性为user且ID为6的实例的CustomerSettings实例。

我的猜测是,您所运行的内容与发布的内容之间存在脱节。如果没有,则调用create_customer_settings,其中instance参数是CustomerSettings的实例。

答案 1 :(得分:0)

我仔细回顾了回溯。 update_customer_settings事件CustomerSettings成功创建post_save模型后,正在调用先前为User工作的方法,在这种情况下,实例确实是CustomerSettings

对此我感到抱歉。你们都为我指明了正确的方向,谢谢。我需要以一种截然不同的方式来处理这个问题。

回溯

File "/Users/my_folder/my_app/my_app/models.py", line 44, in update_customer_settings
CustomerSettings.objects.create(user=instance)
ValueError: Cannot assign "<CustomerSettings: CustomerSettings object (14)>": "CustomerSettings.user" must be a "User" instance.

update_customer_settings

@receiver(post_save, sender=CustomerSettings)
def update_customer_settings(sender, instance, created, **kwargs):
    if created:
        CustomerSettings.objects.create(user=instance)
    instance.customersettings.save()