如何用关联创建新的(未保存的)Django模型? [英] How to create new (unsaved) Django model with associations?
问题描述
我正在为使用现有的前端模板渲染模型的网站的CMS建立一个预览功能。这个模型有一个关联:
class FeatureWork(models.Model):
pre>
name = models.CharField(max_length = 100)
...
class FeatureWorkLink(models.Model):
feature_work = models.ForeignKey(FeatureWork)
在预览视图中,我正在尝试构建模型,以便在模板调用feature.featureworklink_set.all时返回关联的链接。既然这两个模型都没有被保存,所有的标准Django表单技术似乎都是出门的。
这是我到目前为止,但是当我在管理器上调用add方法时,它会爆炸,因为父级还没有保存:
form = FeatureWorkAdminForm(initial = request.POST)
featured = form.save(commit = False)
链接请求.POST ['links']。split(,):
featured.featureworklink_set.add(FeatureWorkLink(image = link))
解决方案为什么不添加:
preview = BooleanField ()
到您的模型,将所有内容保存到数据库,不要查找黑客。这样你可以免费获得草稿。
I'm building a "preview" function into the CMS for my website which uses the existing front-end template to render a model. This model has an association:
class FeatureWork(models.Model): name = models.CharField(max_length=100) ... class FeatureWorkLink(models.Model): feature_work = models.ForeignKey(FeatureWork)
In the view for the preview, I'm trying to build the model such that when the template calls feature.featureworklink_set.all it returns the associated links. Since neither model has been saved yet, all the standard Django form techniques seem to go out the window.
This is what I have so far, but it blows up when I call the add method on the manager, since the parent hasn't been saved yet:
form = FeatureWorkAdminForm(initial=request.POST) featured = form.save(commit=False) for link in request.POST['links'].split(","): featured.featureworklink_set.add(FeatureWorkLink(image=link))
解决方案Why don't you just add:
preview = BooleanField()
to your models, save everything to database and don't look for hacks. This way you can have drafts for free.
这篇关于如何用关联创建新的(未保存的)Django模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!