Django ForeignKey Instance vs Raw ID [英] Django ForeignKey Instance vs Raw ID

查看:95
本文介绍了Django ForeignKey Instance vs Raw ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建新模型时,有没有办法在外键的模型实例中传递?假设我有以下模型:

Is there a way to not have to pass in a model instance for a foreign key when create a new model? Let's say I have the following 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'

稍后的一个帖子请求进入一个视图 - 我知道一个foo记录的id,只是想将一个记录插入到条形表中

The later a post request comes in to a view - I know the the id of a foo record and just want to insert a record into the bar table.

如果我这样做:

new_bar = Bar(info="something important", foo=foo_id)
new_bar.save()

ValueError说无法分配546456487466L:Bar.foo只是一个Foo实例。

I get a ValueError saying "Cannot assign "546456487466L": "Bar.foo" just be a "Foo" instance.

所以,我得到它...希望我有Foo模型的一个实际实例,我明白我可以做一个Foo,然后传入,但是,像ems一样,必须有办法来覆盖这个功能。我已经做了一些搜索和阅读文档,而admin中的raw_id_fields似乎是基本的想法。 (也就是说,允许一个原始ID在这里)。但是,在ForeignKey字段中看不到此选项。

So, I get it... it wants me to have an actual instance of the Foo model. I understand that I can just do a get on Foo and then pass it in. But, there seems like there must be a way to override this functionality. I have done some googling and reading the docs, and raw_id_fields in admin seems to be the basic idea. (which is to say, allow a raw id here). But, don't see this option on the ForeignKey field.

看起来非常低效,不得不做一个往返数据库来获取对象来获取id (我已经有)。我明白,往返行证实数据库中存在id。但是,嘿,这就是为什么我使用RDBMS,并且首先有外键。

It seems very inefficient to have to make a round trip to the database to get an object to get the id (which I already have). I understand that doing the round trip validates that the id exists in the database. But, hey... that's why I'm using a RDBMS and have foreign keys in the first place.

谢谢

推荐答案

new_bar = Bar(info="something important", foo_id=12345)
new_bar.save()

您还可以获取外键值直接。某种优化。

You can also get foreign key values directly. Some kind of optimization.

这篇关于Django ForeignKey Instance vs Raw ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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