Catch-22 when trying to create two-way Django relationship

I want to allow my users to be able to have a selection of avatars and (crucially) force every user to have one which will be used as the main one.

With that in mind, I've got the following (slightly cut down) models:-

class Avatar(models.Model):
    user = models.ForeignKey(User, related_name="avatars", on_delete=models.CASCADE)
    image = models.ImageField()


class User(AbstractUser):
    avatar = models.OneToOneField(Avatar, related_name="+", on_delete=models.CASCADE)

The problem is, I now can't create a User without first creating an Avatar for that User. But I can't create an Avatar without a User. Having spent ages looking at it, I can't see how I can do this without allowing one of these relationships to be null, which seems wrong somehow.

Is there another way to do it?

There is not issue with using a null value so your field would like this :

avatar = models.OneToOneField(Avatar, related_name="+", null=True, blank=True, on_delete=models.CASCADE)

What you can do however is setting a default avatar for a user in the OneToOnefield

default_object = YourAvatarObject    
avatar = models.OneToOneField(Avatar, related_name="+", default=Default_object, on_delete=models.CASCADE)
Back to Top