为什么相关的 create() 使用 Django ORM 检查 id?
Why is related create() checking for id using Django ORM?
我收到此错误:
DETAIL: Key (user_id)=(1) already exists.
当我 运行:
from records.models import Profile
from django.contrib.auth.models import User
users = User.objects.all()
for user in users:
p = Profile.objects.create(user=user)
我正在尝试为每个现有用户创建一个配置文件。
个人资料如下所示:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
auto_complete_look_up_field = models.CharField(max_length=200,db_column='AutoCompleteLookUpField', blank=True, null=True)
这里发生了什么?我会期望user_id存在;那是我要分配给配置文件的用户。为什么这甚至是一个错误?
如果用户的 Profile
已经存在,您将收到此错误。你可以通过使用 get_or_create
来解决这个问题,它只会创建新的 Profile
如果一个不存在
profile, created = Profile.objects.get_or_create(user=user)
我收到此错误:
DETAIL: Key (user_id)=(1) already exists.
当我 运行:
from records.models import Profile
from django.contrib.auth.models import User
users = User.objects.all()
for user in users:
p = Profile.objects.create(user=user)
我正在尝试为每个现有用户创建一个配置文件。
个人资料如下所示:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
auto_complete_look_up_field = models.CharField(max_length=200,db_column='AutoCompleteLookUpField', blank=True, null=True)
这里发生了什么?我会期望user_id存在;那是我要分配给配置文件的用户。为什么这甚至是一个错误?
如果用户的 Profile
已经存在,您将收到此错误。你可以通过使用 get_or_create
来解决这个问题,它只会创建新的 Profile
如果一个不存在
profile, created = Profile.objects.get_or_create(user=user)