views:

70

answers:

1

I have two models Property and Image, related by foreign key such that each Property has multiple instances of Image. I'm trying to retrieve a queryset of all the properties - listing all fields - and the number of images that each property has. I am aware that I could do this as two distinct queries, but I don't feel that this is a particularly elegant approach, and is proving a little inefficient as this information is being retrieved via XMLHttpRequest.

The models are defined as follows:

class Property(models.Model):
    title = models.CharField('title', max_length=255)
    created = models.DateTimeField('created', auto_now_add=True)
    modified = models.DateTimeField('modified', auto_now=True)

    class Meta:
        pass


class Image(models.Model):
    prop_id = models.ForeignKey(Property)
    image_file = models.ImageField('image file', upload_to='/path/to/image/')

    class Meta:
        pass

I have followed the answer posted here: http://stackoverflow.com/questions/2766510/django-aggregation-across-reverse-relationship, as I believe this was a similar problem, but I've found that this returns an empty queryset.

Thanks for any help anyone can offer.

EDIT:

The query I ran was:

Property.objects.all().annotate(image_count=Count('image')).order_by('-image_count')

EDIT 2:

After some experimentation, I have found a solution, though I'm pretty sure that this qualifies as a bug / non-documented issue:

Property.objects.all().annotate(Count('image')).order_by('-image__count')
Property.objects.all().annotate(total_images=Count('image')).order_by('-total_images')

These both work, but naming the annotation image_count did not. Without delving into the Django source, I can't really speculate as to why that's happening.

A: 

The code you've posted should work - in any case, it should not return an empty queryset as annotate doesn't affect the filtering of the main query.

Silly question, but are you sure there are Property elements in the database?

Daniel Roseman
About 200 of them, and almost 9000 image objects, so I'm not sure what's going on here.
Gary Chambers
Accepted, as your answer (on the other question) is correct, and put me on the right track. Thanks.
Gary Chambers