Can I create a OneToOneField that will create an object if it doesn't 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 relationship with a class User

from a Django module auth

. This association is optional; however, thanks to some legacy code and some manual messing around with the database, there are times when the user does not have an associated subscription, which means this code looks like this:

sub = user.subscription

      

will throw an exception DoesNotExist

. However, most of the codebase assumes that each user has an associated object Subscription

.

Is there a way to subclass OneToOneField

so that if the associated object Subscription

does not exist in the database, I create it and return it when it is called user.subscription

, rather than throwing an exception?

+3


source to share


2 answers


The correct way to do this is to catch the signal post_save

by creating an object as needed.



+1


source


Add a property with a name subscription

and in getter

create the link you need, for this you might have to do a monkey patch, better alternatives



  • refactor your code and add a utility function to get a subscription
  • edit your code and add proxy model for user
  • Just fix the db once
0


source







All Articles