Dav*_*d S 14 django django-models
有没有办法在创建新模型时不必传入外键的模型实例?假设我有以下型号:
class Foo(models.Model):
description = models.CharField(max_length=100)
class Meta:
db_table = u'foo'
class Bar(models.Model):
info = models.CharField(max_length=100)
foo = models.ForeignKey('Foo')
class Meta:
db_table = u'bar'
Run Code Online (Sandbox Code Playgroud)
后一个帖子请求进入视图 - 我知道foo记录的id,只是想在条形图表中插入一条记录.
如果我做:
new_bar = Bar(info="something important", foo=foo_id)
new_bar.save()
Run Code Online (Sandbox Code Playgroud)
我得到一个ValueError说"无法分配"546456487466L":"Bar.foo"只是一个"Foo"实例.
所以,我明白了...它希望我有一个Foo模型的实际实例.我知道我可以做一个Foo然后传入它.但是,似乎必须有一种方法来覆盖这个功能.我做了一些谷歌搜索和阅读文档,管理员中的raw_id_fields似乎是基本的想法.(也就是说,在这里允许原始id).但是,不要在ForeignKey字段上看到此选项.
对数据库进行往返以获取对象来获取id(我已经拥有)似乎非常低效.我知道进行往返验证了数据库中存在的id.但是,嘿......这就是我使用RDBMS并首先拥有外键的原因.
谢谢
San*_*4ez 21
new_bar = Bar(info="something important", foo_id=12345)
new_bar.save()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12034 次 |
最近记录: |