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
new_bar = Bar(info="something important", foo_id=12345)
new_bar.save()
You can also get foreign key values directly. Some kind of optimization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With