0

I have two models related with ForeignKey and I am using select_related to fetch data from them:

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__()

My query is as follows:

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

Now, as explained in the select_related documentation, it fetches related objects at once and does not hit the database again. But in my case brainframe.fk_brainframe_parent hits the database every time. But it should not as I have fetched data using select_related. So am I doing something wrong here?

1 Answer 1

1

You're using the (lowercased) name of the model in your call to select_related. Instead, use the name of the field, e.g. Adjacency.objects.select_related('fk_brainframe_parent').

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.