Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Prefetch in Django

I have the current model in my Django app:

class Referentiel(models.Model):
    code = models.CharField(max_length=50)
    libelle = models.CharField(max_length=100)


class Reference(models.Model):
    referentiel = models.ForeignKey('Referentiel', related_name='reference_set')
    clef = models.CharField(max_length=50)


class ValeurReference(models.Model):
    reference = models.ForeignKey('Reference', related_name='valeur_set')
    valeur = models.DecimalField(max_digits=15, decimal_places=5)
    date_fin = models.DateField(blank=True, null=True)

And I wish to retrieve values of a Referentiel, so I do something like that:

Referentiel.objects.filter(code='whatever_code').prefetch_related(Prefetch('reference_set__valeur_set', to_attr='valeurs'))

But I have the following error when trying to get my values:

AttributeError: 'Referentiel' object has no attribute 'valeurs'

Django version: 1.7.4 Python version: 3.4.2

Thanks for any advice.

like image 988
Marc Debureaux Avatar asked Jul 01 '26 21:07

Marc Debureaux


1 Answers

I know it's an old question, but I encountered such error recently as well.

The problem is that valeurs are not assigned to Referentiel object, but to the reference_set.

So in this case, given that you have a queryset like this:

queryset = (
    Referentiel
    .objects
    .filter(code='whatever_code')
    .prefetch_related(Prefetch('reference_set__valeur_set', to_attr='valeurs'))
)

Instead of doing:

queryset[0].valeurs

You have to do:

queryset[0].reference_set.all()[0].valeurs

Unfortunately the to_attr may be misleading and scenario with nested lookup is not mentioned in the documentation.

like image 64
paffer Avatar answered Jul 03 '26 10:07

paffer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!