开发者

Django ForeignModels

开发者 https://www.devze.com 2022-12-28 15:43 出处:网络
How do I get/set foreign key fields on a model object without t开发者_运维百科ouching the database and loading the related object?Django actually appends an \'_id\' to ForeignKey field names and with

How do I get/set foreign key fields on a model object without t开发者_运维百科ouching the database and loading the related object?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消