尚未创建的模型的Django外键 [英] Django Foreign Key to a yet-to-be created Model

查看:98
本文介绍了尚未创建的模型的Django外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Django中有没有办法将模型与另一个尚未创建的外键模型进行关联。两个模型将使用相同的HTML页面中的相同ModelForm来创建。



例如

 code> class Team(models.Model):
name = forms.CharField
...

class Player(models.Model):
name = forms.CharField()
key = forms.ForeignKey(Team)
...

基本上,我想知道这两个模型是否可以放在同一个HTML页面中的< form> ...< / form> 中。

解决方案

外键是引用模型的主键的引用,因此目标需要存在。您需要保存第一个表单,然后在保存之前更新第二个表单上的引用。要从保存到数据库的表单中获取模型实例,可以使用

  instance = form.save(commit = False )

然后您需要自己保存实例

  instance.save()

如果你是使用多对多字段,您需要查看 save_m2m


I'm wondering if there's way in Django to associate a model to another, yet-to-be created model with a foreign key. Both model would be created using the same ModelForm in the same HTML page.

e.g.

class Team(models.Model):
    name = forms.CharField
    ...

class Player(models.Model):
    name = forms.CharField()
    key = forms.ForeignKey(Team)
    ...

Basically, I'm wondering if both these models can be put in the same <form>...</form> in one HTML page.

解决方案

a foreign key is a reference to the primary key of the referenced model, so the target needs to exist. you need to save the first form, and then update the reference on the second one before saving. to get a model instance from a form without saving to the db, you can use

instance = form.save(commit=False)

you then need to save the instance yourself

instance.save()

and if you are using many-to-many fields, you need to look at save_m2m

这篇关于尚未创建的模型的Django外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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