How do I get/set foreign key fields on a model object without touching the database and loading the related object?
A:
You can use .select_related() to load up related models as part of the initial query. You can then get/set properties without a database hit.
Remember that to save stuff, you will need to hit the database.
For details on how to use it, try the documentation.
Matthew Schinckel
2010-04-28 02:27:22
.select_related() will generate a join, which I don't need to do. The foreign key id is already a field in the tuple that represents the object, I just need to get/set that id. I don't need to get/set any fields in the related tuple.
limscoder
2010-04-28 20:24:26
I guess I misunderstood what you has asked: I thought you were asking how to set fields on a related model.
Matthew Schinckel
2010-04-29 01:00:42
+1
A:
Django actually appends an '_id' to ForeignKey field names and with 'field_name_id' you can get or set the integer id value directly:
class MyModel(models.Model):
field = models.ForeignKey(MyOtherModel)
mymodel_instance = MyModel.objects.get(pk=1)
# queries database for related object and the result is a MyOtherModel instance
print mymodel_instance.field
# result is simply the integer id value, does not do any query
print mymodel_instance.field_id
Béres Botond
2010-04-28 14:29:58