开发者

Annotate a django query via a reverse relationship

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: 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('-imag开发者_如何学Ce__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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜