当我更改__unicode__方法的默认返回以传递倍数的外键时会发生什么

时间:2015-09-23 00:45:28

标签: django django-models

我想知道,就数据库效率而言,如果我编辑return __unicode__方法并执行以下操作:

class AnyModel(models.Model):
    a_field = models.ForeignKey(A)
    b_field = models.ForeignKey(B)

    def __unicode__(self):
        return "A - B: %s - %s " % (self.a_field.a2.a3, self.b_field.b2.b3)

因此,__unicode__方法将命中外键的外键的外键,获取一个字符串然后将其返回。

... 太贵了吗?我应该遵循什么标准?我可以使用任何一般性建议吗?最好不要编写这种__unicode__方法吗?

1 个答案:

答案 0 :(得分:2)

这就是这种结构发生的事情:

AddItemToListView

点击:

ActivateEditingAction

但是,如果你这样做,那么:

def __unicode__(self):
        return "A - B: %s - %s " % (self.a_field.a2.a3, self.b_field.b2.b3)

执行行时:

(0.000) QUERY = 'SELECT "core_a"."id", "core_a"."a2_id" FROM "core_a" WHERE "core_a"."id" = %s' - PARAMS = (2,); args=(2,)
(0.000) QUERY = 'SELECT "core_a2"."id", "core_a2"."a3_id" FROM "core_a2" WHERE "core_a2"."id" = %s' - PARAMS = (1,); args=(1,)
(0.012) QUERY = 'SELECT "core_a3"."id" FROM "core_a3" WHERE "core_a3"."id" = %s' - PARAMS = (1,); args=(1,)
(0.000) QUERY = 'SELECT "core_b"."id", "core_b"."b2_id" FROM "core_b" WHERE "core_b"."id" = %s' - PARAMS = (1,); args=(1,)
(0.000) QUERY = 'SELECT "core_b2"."id", "core_b2"."b3_id" FROM "core_b2" WHERE "core_b2"."id" = %s' - PARAMS = (1,); args=(1,)
(0.005) QUERY = 'SELECT "core_b3"."id" FROM "core_b3" WHERE "core_b3"."id" = %s' - PARAMS = (1,); args=(1,)

1点击:

def __unicode__(self):
        a_relation = AnyModel.objects.select_related('a_field__a2__a3').get(pk=self.pk)
        b_relation = AnyModel.objects.select_related('b_field__b2__b3').get(pk=self.pk)
        return "A - B: %s - %s " % (a_relation.a_field.a2.a3, b_relation.b_field.b2.b3)

并执行第二行时:

a_relation = AnyModel.objects.select_related('a_field__a2__a3').get(pk=self.pk)

+1点击:

(0.000) QUERY = 'SELECT "core_anymodel"."id", "core_anymodel"."a_field_id", "core_anymodel"."b_field_id", "core_a"."id", "core_a"."a2_id", "core_a2"."id", "core_a2"."a3_id", "core_a3"."id" FROM "core_anymodel" INNER JOIN "core_a" ON ( "core_anymodel"."a_field_id" = "core_a"."id" ) INNER JOIN "core_a2" ON ( "core_a"."a2_id" = "core_a2"."id" ) INNER JOIN "core_a3" ON ( "core_a2"."a3_id" = "core_a3"."id" ) WHERE "core_anymodel"."id" = %s' - PARAMS = (1,); args=(1,)

执行时

b_relation = AnyModel.objects.select_related('b_field__b2__b3').get(pk=self.pk)

未点击数据库。

1 - 修改

您可以加入:

(0.000) QUERY = 'SELECT "core_anymodel"."id", "core_anymodel"."a_field_id", "core_anymodel"."b_field_id", "core_b"."id", "core_b"."b2_id", "core_b2"."id", "core_b2"."b3_id", "core_b3"."id" FROM "core_anymodel" INNER JOIN "core_b" ON ( "core_anymodel"."b_field_id" = "core_b"."id" ) INNER JOIN "core_b2" ON ( "core_b"."b2_id" = "core_b2"."id" ) INNER JOIN "core_b3" ON ( "core_b2"."b3_id" = "core_b3"."id" ) WHERE "core_anymodel"."id" = %s' - PARAMS = (1,); args=(1,)

并且只会打一次。

return "A - B: %s - %s " % (self.a_field.a2.a3, self.b_field.b2.b3)