尚未创建的模型的Django外键 [英] Django Foreign Key to a yet-to-be created Model
问题描述
例如
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屋!