Django post_save接收器不会保存外键

时间:2017-09-15 13:07:16

标签: python django django-models

我有三个模型: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()

正如所料,它在数据库中创建了两个条目:UserProfileGameCharacterGameCharacter的外键是 < em> not 已保存,它在数据库中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()

我使用 MySQL InnoDB 作为存储引擎。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

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

即:

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