在创建模型时创建OneToOne实例 [英] Create OneToOne instance on model creation
问题描述
class User(models.Model):
name = models.CharField(max_length = 200)
class FavouriteList(models.Model):
user = models.OneToOneField(User)
favorites = models。 ManyToManyField(Favorite,blank = True)
当创建新用户时,我想确保用户有一个 FavouriteList
。有没有人知道如何确保一个模型有一个子对象(例如<$ code> FavouriteList )当创建它时
是使用Django信号系统。您可以将用户模型的post_save信号附加一个信号处理程序(只是某个功能),并在该回调内创建收藏列表。
从django.db.models.signals导入post_save
从django.dispatch导入接收器
从django.contrib.auth.models导入用户
@receiver( post_save,sender = User)
def create_favorites(发件人,实例,创建,** kwargs):
如果创建:
Favorites.objects.create(user = instance)
以上是从 Django signal docs 。请务必仔细阅读信号文档,因为有几个问题可以阻止您,例如您的信号处理程序代码应该在哪里生活,以及如何避免重复的处理程序。
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)
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.
Does anyone know how I can ensure that a model has a child object (e.g. FavouriteList
) when it is created?
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)
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屋!