简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM