Django可以自动创建一个相关的一对一模型吗? [英] Can Django automatically create a related one-to-one model?

查看:96
本文介绍了Django可以自动创建一个相关的一对一模型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在不同的应用程序中有两个模型:modelA和modelB。他们有一对一的关系。有没有一种方法django可以自动创建和保存ModelB,当modelA被保存?

  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。



编辑说,模型在不同的应用程序。

解决方案

查看 Django的恼人。从文档中:

  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函数这样的宝石)


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)

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.

解决方案

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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆