Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a OneToOneField that will create an object if it does not exist?

I am working with a Django model that looks like this:

class Subscription(models.Model):
    user = models.OneToOneField(User)

That is, it has a one-to-one association with the User class from Django's auth module. This association is not optional; however, thanks to some legacy code and some manual tinkering with the database, there are cases in which a user does not have an associated subscription, which means that code like this:

sub = user.subscription

will throw a DoesNotExist exception. However, much of the codebase assumes that every user has an associated Subscription object.

Is there a way I could subclass OneToOneField such that, if the associated Subscription object does not exist in the database, I will create one and return it when user.subscription is called, instead of throwing an exception?

like image 909
mipadi Avatar asked Nov 21 '25 12:11

mipadi


1 Answers

The correct way to do this is to catch the post_save signal, creating an object if necessary.

like image 107
Ignacio Vazquez-Abrams Avatar answered Nov 24 '25 04:11

Ignacio Vazquez-Abrams