Django只使用ForeignKey中的一些字段

时间:2012-10-16 11:02:17

标签: django django-models django-admin

我有三个班级

 Class Company(models.Model):
     name     = CharField( max_length = 26 , blank = True)
     #(...)

 class Person(models.Model):
     name     = CharField( max_length = 26 , blank = True)
     function = CharField( max_length = 50 , blank = True)
     company  = ForeignKey ( Company , related_name = 'persons' )
     # All the company table inside the data base is loaded in order to make the query,
     # This make a HUGE amount of data and takes too many time...
     # (...)
     def __unicode__(self):
          # caption uses both name and company__name fields but no other fields
          return self.name + '(' + self.company.name + ')'

 class Contact(models.Model):
      person  =  ForeignKey ( Person )

为了优化表演,我希望使用最新人物字段

Person.objects.all().only('name', 'company__name')

作为queryset。有可能吗?

2 个答案:

答案 0 :(得分:0)

您可以使用values方法,该方法返回QuerySet的子类,名为ValuesQuerySet。

Person.objects.all().values('name', 'company__name')

了解更多信息Django Doc

答案 1 :(得分:0)

使用代理模型:

 class Person_short_manager(Manager):
    def get_query_set(self):
        return super(self, Person_short_manager).get_query_set().only('name','company__name')

 class Person_short(Person):
    objects = Person_short_manager(Manager)
    class Meta:
         proxy = True

然后替换

 person  =  ForeignKey ( Person )

通过

 person  =  ForeignKey ( Person_short )