简体   繁体   English

Django OneToOne字段的默认关系

[英]Default relation for Django OneToOne Field

I'm trying to create a couple django models with a one to one relation. 我正在尝试创建一对一的django模型。 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. 如果创建MyObject并访问MyObject.data,它将返回None。 I was hoping there was a way I can have it return a MyData object (just default reference). 我希望有一种方法可以让它返回MyData对象(只是默认引用)。

I'd like MyObject to automatically have a related MyData object. 我希望MyObject自动具有一个相关的MyData对象。 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? 有没有办法让我执行此操作,还是需要每次检查是否有相关的MyData对象?

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. 当然,您的Mydata现在应该可以接受None作为其类型了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM