在模型创建时创建 OneToOne 实例 [英] Create OneToOne instance on model creation
问题描述
我正在构建我的第一个 django 应用程序.我有一个用户,该用户有一个收藏夹列表.一个用户只有一个收藏夹列表,该列表只属于该用户.
I'm building my first django app. I have a user, and the user has a list of favourites. A user has exactly one list of favourites, and that list belongs exclusively to that user.
class User(models.Model):
name = models.CharField(max_length=200)
class FavouriteList(models.Model):
user = models.OneToOneField(User)
favourites = models.ManyToManyField(Favourite, blank=True)
当创建一个新用户时,我想确保该用户有一个 FavouriteList
.我在 Django 文档中环顾四周,但运气不佳.
When a new user is created, I want to ensure that the user has a FavouriteList
. I've looked around in the Django documentation and haven't had much luck.
有谁知道我如何确保模型在创建时具有子对象(例如 FavouriteList
)?
Does anyone know how I can ensure that a model has a child object (e.g. FavouriteList
) when it is created?
推荐答案
最常见的方法是使用 Django 信号系统.您可以将信号处理程序(只是某个地方的一个函数)附加到用户模型的 post_save 信号,并在该回调中创建您的收藏夹列表.
The most common way to accomplish this is to use the Django signals system. You can attach a signal handler (just a function somewhere) to the post_save signal for the User model, and create your favorites list inside of that callback.
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
@receiver(post_save, sender=User)
def create_favorites(sender, instance, created, **kwargs):
if created:
Favorites.objects.create(user=instance)
以上内容改编自 Django 信号文档.请务必完整阅读信号文档,因为有一些问题可能会阻碍您,例如您的信号处理程序代码应该放在何处以及如何避免重复处理程序.
The above was adapted from the Django signals docs. Be sure to read the signals docs entirely because there are a few issues that can snag you such as where your signal handler code should live and how to avoid duplicate handlers.
这篇关于在模型创建时创建 OneToOne 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!