Django模型中的查询

2024-03-28 19:29:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个与ForeignKey相关的模型,我正在使用select_related从它们获取数据:

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获取数据那样。我是不是做错什么了?你知道吗


Tags: selftruereturnmodelsselectnullparenttextfield
1条回答
网友
1楼 · 发布于 2024-03-28 19:29:48

在对select_related的调用中使用的是模型的(小写)名称。相反,使用字段的名称,例如Adjacency.objects.select_related('fk_brainframe_parent')。你知道吗

相关问题 更多 >