2015-03-19 153 views
0

我有ForeignKey相關的兩款車型,我使用select_related從他們那裏獲取數據:查詢在Django模型

class Translation(models.Model): 
    pk_translation = UUIDField(auto=True, primary_key=True, serialize=True, hyphenate=True) 
    en = models.TextField('English', blank = True, null = True) 
    fr = models.TextField('French', blank = True, null = True) 
    de = models.TextField('German', blank = True, null = True) 
    it = models.TextField('Italian', blank = True, null = True) 
    creationLanguage = models.CharField(max_length=3, choices=s.LANGUAGES, blank = True, null = True) 

    def __str__(self):    # __unicode__ on Python 2 
     if self.creationLanguage is not None: 
      return getattr(self, str(self.creationLanguage)) 
     else: 
      return str(self.en) 

class Brainframe(models.Model): 
    pk_brainframe = UUIDField(auto=True, primary_key=True, serialize=True, hyphenate=True) 
    title = models.OneToOneField(Translation, related_name='Brainframe.title') 
    description = models.OneToOneField(Translation, related_name='Brainframe.description') 

    def __str__(self):    # __unicode__ on Python 2 
     return self.title.__str__() 

class Adjacency(models.Model): 
    pk_adjacency = UUIDField(auto=True, primary_key=True, hyphenate=True) 
    fk_brainframe_parent = models.ForeignKey('Brainframe', related_name='Adjacency.parent') 
    fk_brainframe_child = models.ForeignKey('Brainframe', related_name='Adjacency.child') 

    def __str__(self):    # __unicode__ on Python 2 
     return self.fk_brainframe_child.__str__() 

我的查詢如下:現在

root_id = Brainframe.objects.select_related('translation').get(pk=brainframe_id) 

brainframes = Adjacency.objects.select_related('brainframe').filter(fk_brainframe_parent=root_id) 

for brainframe in brainframes: 
     print brainframe.fk_brainframe_parent #it hit the database 

,如解釋select_related文檔,它立即獲取相關對象,並且不會再次訪問數據庫。但在我的情況下,每次點擊數據庫brainframe.fk_brainframe_parent。但它不應該像我使用select_related獲取數據一樣。那麼我在這裏做錯了什麼?

回答

1

您在撥打select_related時正在使用模型的(小寫)名稱。相反,使用該字段的名稱,例如Adjacency.objects.select_related('fk_brainframe_parent')