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


正如预期的那样,它在数据库中创建了两个条目,分别是UserProfileGameCharacter,但是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()


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

任何想法?

最佳答案

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

即:

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

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

10-12 03:10