Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

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.

if I do:

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

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

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.

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.

Thanks

like image 310
David S Avatar asked May 16 '12 16:05

David S


1 Answers

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

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

like image 148
San4ez Avatar answered Oct 04 '22 16:10

San4ez