gpt4 book ai didi

python - Django post_save 接收器不会保存外键

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

我有三个模型:User(来自django.contrib.auth.models)、UserProfileGameCharacter >.

我设置了以下接收器,以便在创建User时,也会自动创建UserProfileGameCharacter

@receiver(models.signals.post_save, sender=User)
def create_user_profile(sender, instance, created, *args, **kwargs):
if created:
user_profile = UserProfile()
user_profile.user = instance
user_profile.money = 0

user_profile.save()


@receiver(models.signals.post_save, sender=UserProfile)
def create_user_profile_character(sender, instance, created, *args, **kwargs):
if created:
instance.character = GameCharacter() # Doesn't work, `character_id` is NULL in databse
instance.character.save()
instance.save()

正如预期的那样,它在数据库中创建了两个条目,一个 UserProfile 和一个 GameCharacter但是 GameCharacter 的外键 保存,数据库中为NULL

就好像 instance.character = GameCharacter() 行不存在。

我的模型:

class GameCharacter(models.Model):
nickname = models.CharField(max_length=255, null=True, blank=True, default=None)
server = models.ForeignKey(GameServer, on_delete=models.PROTECT, null=True, blank=True, default=None)
is_bot = models.BooleanField(default=False)
position = models.CharField(max_length=255, null=True, blank=True, default=None)

class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
character = models.ForeignKey(GameCharacter, null=True, blank=True, on_delete=models.SET_NULL)
money = models.BigIntegerField()

我使用MySQLInnoDB作为存储引擎。

有什么想法吗?

最佳答案

首先您必须创建一个 GameCharacter 对象。然后将其链接到instance.character

即:

character = GameCharacter()
character.save()
instance.character = character
instance.save()

关于python - Django post_save 接收器不会保存外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46240352/

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