Django 可以自动创建相关的一对一模型吗? [英] Can Django automatically create a related one-to-one model?
问题描述
我在不同的应用中有两个模型:ModelA
和 ModelB
.他们是一对一的关系.当ModelA
被保存时,django有没有办法自动创建和保存ModelB
?
I have two models in different apps: ModelA
and ModelB
. They have a one-to-one relationship. Is there a way django can automatically create and save ModelB
when ModelA
is saved?
class ModelA(models.Model):
name = models.CharField(max_length=30)
class ModelB(models.Model):
thing = models.OneToOneField(ModelA, primary_key=True)
num_widgets = IntegerField(default=0)
当我保存新的 ModelA
时,我希望它的条目自动保存在 ModelB
中.我怎样才能做到这一点?有没有办法在 ModelA
中指定它?或者这是不可能的,我只需要在视图中创建和保存 ModelB
?
When I save a new ModelA
I want a entry for it to be saved automatically in ModelB
. How can I do this? Is there a way to specify that in ModelA
? Or is this not possible, and I would just need to create and save ModelB
in the view?
编辑说模型在不同的应用程序中.
Edited to say the models are in different apps.
推荐答案
查看 django-annoying.来自文档:
Take a look at the AutoOneToOneField
in django-annoying. From the docs:
from annoying.fields import AutoOneToOneField
class MyProfile(models.Model):
user = AutoOneToOneField(User, primary_key=True)
home_page = models.URLField(max_length=255)
icq = models.CharField(max_length=255)
(django-annoying 是一个很棒的小库,其中包含诸如 render_to 装饰器
和 get_object_or_None
和 get_config
函数之类的宝石)
(django-annoying is a great little library that includes gems like the render_to decorator
and the get_object_or_None
and get_config
functions)
这篇关于Django 可以自动创建相关的一对一模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!