Automatically Creating Related Objects in Django

Screen Shot 2018-04-28 at 10.19.11 PM

At its core, SafeButler is a software technology company. Our engineers are building sophisticated software to fulfill our mission of managing and automating insurance for consumers. From time to time, we’ll publish technical tips from our engineers as they solve interesting problems.

Today’s tip is about how to automatically create related objects in Django. Imagine a database model has a table for User and another table for UserProfile. There is a 1:1 relationship between the two tables. Ideally, whenever a User object is saved, its corresponding UserProfile should be created, linked and saved automatically. That way, the User object won’t have a null UserProfile.

Using Django’s signal provides a nice solution. As illustrated below, we use @receiver decorator to automatically create a UserProfile object upon creation of a User object. The two objects are linked to each other too. Done. Nice and simple.

from django.db.models.signals import post_save
from django.dispatch import receiver


@receiver(post_save, sender=user)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)


@receiver(post_save, sender=user)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

Leave a Reply