Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create OneToOne instance on model creation

Tags:

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?

like image 805
NT3RP Avatar asked Apr 09 '11 21:04

NT3RP


People also ask

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

What is OneToOneField in Django models?

One-to-one fields: This is used when one record of a model A is related to exactly one record of another model B. This field can be useful as a primary key of an object if that object extends another object in some way.


1 Answers

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.

like image 81
shadfc Avatar answered Oct 16 '22 05:10

shadfc