use IDs instead of instances to create new objects with foreign keys

I want to create a new Django ORM object with three foreign keys. I got the IDs of the foreign rows already, and I mean - that's all I need to fill the foreign key columns in my new row, right? However, I don't seem able to create the new row without hitting the DB three times to instantiate objects out of those IDs.

So what I need to do:

foreign_object = models.ForeignObject.get(pk=foreign_object_id)
a = models.Object1.get_or_create(f = foreign_object)

What I'd like to do:

a = models.Object1.get_or_create(f_id = foreign_object_id)

f_id however is not a field Django recognizes. If I just assign foreign_object_id to f (I think I recall this works in some cases), Django complains that it wants a ForeignObject instance instead of an int.

Any way to do this?

Answers


You need to use the double-underscore notation in this case

eg

a = models.Object1.get_or_create(f__pk=foreign_object_id)

Need Your Help

Swing JMenu acting strange

java swing user-interface

I have recently started making a minesweeper-like game in java with swing (using eclipse WindowBuilder), and in the app there is an ordinary JFrame with a JMenu with options in it. It works as it s...

Serialize java.lang.Throwable along with stack trace, causes chain and related stack traces

java exception gwt serialization stack-trace

I'm writing GWT application where I need to send instance of java.lang.Throwable (with chain of it's causes and all stack traces respectively) using GWT RPC which uses standard Java serialization

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.