Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default relation for Django OneToOne Field

Tags:

python

django

I'm trying to create a couple django models with a one to one relation. However I'm trying to get it so the related one to one model is automatically created. If I have something simple like this:

class MyObject(models.Model):
    data = models.OneToOneField('MyData', related_name='my_object')

class MyData(models.Model):
    info = models.TextField(null=True)

If I create a MyObject and access MyObject.data it will return None. I was hoping there was a way I can have it return a MyData object (just default reference).

I'd like MyObject to automatically have a related MyData object. Is there a way for me to do this or do I need to check every time to see if there's a related MyData object?

like image 815
kevin.w.johnson Avatar asked Dec 05 '25 03:12

kevin.w.johnson


1 Answers

Have you seen the official doc?

d = MyData(info='whatever')
o = MyObject(data=d)

How can it be automatic if info text field has to be filled in?

after seeing your edit:
you can probably set my data to be null

o = MyObject(data=Mydata(info=None))

of course, your Mydata should now be able to accept None as their type.

like image 84
taesu Avatar answered Dec 07 '25 17:12

taesu