Automatically create OneToOneField in Django

The Django-annoying package contains various useful functions and AutoOneToOneField is one of them.

Using AutoOneToOneField a related object is automatically created when the parent object is created.

In this example, whenever a new user account is created, a corresponding Profile is also created

Important: The child object is not created unless it is accessed.

1. Install

pip install django-annoying

2. In your models

from django.contrib.auth.models import User
from annoying.fields import AutoOneToOneField

class Profile(models.Model):
user = AutoOneToOneField(User, primary_key=True)
name = models.CharField(max_length=255, blank=True)
age = models.IntegerField(blank=True, null=True)

3. Accessing the Child Object

As I mentioned that the child object won’t be created usless it is accessed.

so, in you view you might wanna do something like this.

def saveprofile(request):
u = User.objects.get(username=request.user)
print(u.player) #accessing child object

That’s it!

Leave a Reply

Your email address will not be published.