1

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?

2 Answers 2

2

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.

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

Comments

1

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).

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.