gpt4 book ai didi

python - Django - 为什么这个模型没有创建 pk 并提示相关模型的 pk 的完整性?

转载 作者:行者123 更新时间:2023-11-30 22:11:37 28 4
gpt4 key购买 nike

为什么这个模型没有创建 pk 并提示相关模型的 pk 的完整性?

创建 UserProfile 的新实例时,它不会创建主键。

我正在遵循一对一的说明 in this tutorial (这就是所有 @receiver 的内容)

我的 models.py 中有以下内容:

class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
guid = models.UUIDField(null=True)

@classmethod
def create(cls, first_name, last_name, email, guid=None):
user = User.objects.create(first_name=first_name, last_name=last_name, email=email)
user_profile = cls(user=user, guid=guid) if guid else cls(user=user)
# user_profile.save() ## This didn't work..
return user_profile

def most_recent_device(self):
return self.devices.order_by('-pk').first()

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

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()


class Device(models.Model):
guid = models.UUIDField(null=True)
fcm_token = models.CharField(max_length=4096, null=True)
user_profiles = models.ManyToManyField(UserProfile, related_name='devices')

def most_recent_user(self):
return self.user_profiles.order_by('-pk').first()

@classmethod
def create(cls, guid=None, fcm_token=None, user_profiles=None):
self = cls()
self.save() ## possibly excessive saving trying to get this to work
if guid:
self.guid = guid
if fcm_token:
self.fcm_token = fcm_token
if user_profiles:
for user_profile in user_profiles:
self.user_profiles.add(user_profile.user.pk)
self.save() ## possibly excessive saving trying to get this to work
return self

当我去创建 UserProfile 模型的实例时,不会自动创建 pk。例如,我将其输入到交互式 shell 中:

>>> user_profile = UserProfile.create(
first_name = 'firstname',
last_name = 'lastname',
email = 'firstname.lastname@company.com',
guid = "ed282e0c-4e9d-404b-ba70-8910ec7fe780"
)

然后,当我访问 UserProfile 的主键时,我什么也得不到:

>>> user_profile.pk

有趣的是,pk 是为用户模型创建的:

>>> user_profile.user.pk
3

当我调用user_profile.save()时,出现以下异常:

django.db.utils.IntegrityError: UNIQUE constraint failed: Interface_userprofile.user_id

我做错了什么?/发生什么事了?

这是完整的堆栈跟踪:

>>> user_profile.save()
Traceback (most recent call last):
File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Program Files\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: Interface_userprofile.user_id

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Program Files\Python37\lib\site-packages\django\db\models\base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "C:\Program Files\Python37\lib\site-packages\django\db\models\base.py", line 759, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Program Files\Python37\lib\site-packages\django\db\models\base.py", line 842, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Program Files\Python37\lib\site-packages\django\db\models\base.py", line 880, in _do_insert
using=using, raw=raw)
File "C:\Program Files\Python37\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Program Files\Python37\lib\site-packages\django\db\models\query.py", line 1125, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Program Files\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1285, in execute_sql
cursor.execute(sql, params)
File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Program Files\Python37\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Program Files\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: Interface_userprofile.user_id

最佳答案

我怀疑涉及 instance.profile.save() 的混淆,你的related_name='profile'事实上,在你的教程中,UserProfile称为 Profile .

在教程中,.profile指型号Profile但就你而言.profileuser UserProfile领域.

难道你用的是profile而不是user_profile

我会尝试:

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.user_profile.save()

而不是:

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()

关于python - Django - 为什么这个模型没有创建 pk 并提示相关模型的 pk 的完整性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51367753/

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