[英]How to create model objects of one model automatically when a model object of another has been added in django
Say for example I have a Model called Player.比如说我有一个名为 Player 的模型。 I want Model objects of Player created when new Users are added in django (from
django.contrib.auth.models.User
) such that each User object in User model has its own object in Player model.我希望在 django 中添加新用户(来自
django.contrib.auth.models.User
)时创建 Player 的 Model 对象,以便 User 模型中的每个 User 对象在 Player 模型中都有自己的对象。 I know that I would technically have to use models.ForeignKey()
to create a field in Player model and relate it to the User model and that I don't have to worry about deletion of users if I use the on_delete=models.CASCADE
parameter in models.ForeignKey()
but how do I automatically create these objects with like default values and such.我知道我在技术上必须使用
models.ForeignKey()
在 Player 模型中创建一个字段并将其与 User 模型相关联,如果我使用on_delete=models.CASCADE
,我不必担心删除用户models.ForeignKey()
参数但是我如何使用默认值等自动创建这些对象。 Initially this was my code to do so:最初这是我的代码:
for name in User.objects.all().values_list('username', flat=True):
if name not in Player.objects.all().values_list('player_name', flat=True):
new_player = Player(player_name=name, current_level_no=None, no_of_moves=None)
new_player.save()
else:
pass
But this would give me a DatabaseIntegrityError that "Models aren't loaded yet".但这会给我一个 DatabaseIntegrityError “模型尚未加载”。 So I am confused about what to do or how to go forward.
所以我对做什么或如何前进感到困惑。
As always, I greatly appreciate all answers!一如既往,我非常感谢所有的答案!
Check out Django signals , specifically the post_save signal .查看Django 信号,特别是post_save 信号。 Essentially, Django lets you define a function that will be run whenever your User model is saved.
本质上,Django 允许您定义一个函数,该函数将在您的 User 模型被保存时运行。 You'd use it something like this:
你会像这样使用它:
from django.db.models.signals import post_save
def create_player(sender, instance, created, **kwargs):
if created:
Player.objects.create(user=instance) # instance is the User object
post_save.connect(create_player, sender=User)
Note that if you already have User objects in your database, this won't create Player objects for them;请注意,如果您的数据库中已经有 User 对象,则不会为它们创建 Player 对象; you'll want to do that by running a loop similar to the one you posted in the Django shell (using
python manage.py shell
).您需要通过运行一个类似于您在 Django shell 中发布的循环(使用
python manage.py shell
)来做到这一点。 The signal will run on every subsequent save of a user model.该信号将在用户模型的每次后续保存中运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.