我想在实例化User模型时实例化Blog模型,并通过OneToOneField将Blog模型的新实例与刚创建的User模型实例相关联(并保存在数据库中)。
当我创建用户模型的新实例并通过OneToOneField将它们关联时,我总是希望创建Blog模型的新实例。
class User(AbstractUser):
# some logic to create a new instance of the Blog model
# and associating it with a just created instance of the User
# by the OneToOneField
class Blog(models.Model):
author = OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
我如何得到它?
提前谢谢!
答案 0 :(得分:0)
您可以为此使用信号(https://docs.djangoproject.com/en/2.2/ref/signals/)。因此,在您的情况下,它可能看起来像这样:
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User)
def create_blog(sender, instance, created, **kwargs):
if created:
Blog.objects.create(author=instance)