Adam
Adam

Reputation: 3128

select_related Issue

Here are my models:

class Brand(models.Model):
    name         = models.CharField(max_length=30)
    order        = models.SmallIntegerField()

class FeatureGroup(models.Model):
    name         = models.CharField(max_length=30)

class Feature(models.Model):
    name         = models.CharField(max_length=30, blank=True)
    order        = models.SmallIntegerField()
    group        = models.ForeignKey(FeatureGroup)

class FeatureDetail(models.Model):
    description         = models.TextField()
    feature             = models.ForeignKey(Feature)

class Phone(models.Model):
    name         = models.CharField(max_length=30)
    brand        = models.ForeignKey(Brand)
    features     = models.ManyToManyField(FeatureDetail)

I an trying to get features and feature details of the current phone and loop over data pairs but unable to do so.

I tried this and it only works for getting the brand:

p = get_object_or_404(Phone.objects.select_related('brand', 'feature__featuredetail'), id=id)

And when doing:

print p.featuredetail_set.all()

I get and this error:

Django Version: 1.4.3
Exception Type: AttributeError
Exception Value:    
'Phone' object has no attribute 'featuredetail_set'

What's wrong?

Upvotes: 1

Views: 4162

Answers (2)

Tianissimo
Tianissimo

Reputation: 1270

You can't use a class name as a parameter to select_related. The parameter must be a string of your model field.

In your case, it should be 'features__feature'

Another problem is that select_related cannot follow many-to-many relationship. That's why prefetch_related comes.

Therefore, your queryset would be:

Phone.objects.select_related('brand').prefetch_related('features__feature')

Note that prefetch_related creates an additional query and does the joining in Python.

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599490

Your relation is called features, not featuredetail_set.

Note this has nothing to do with select_related, which does nothing in this case (it only works on forward ForeignKeys, anyway).

Upvotes: 1

Related Questions