Aggregate and foreign key

I’ve got the following model

class Listing(models.Model):
    ...
    category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True, related_name='listing_categories', related_query_name='listing_category')
    ...

and in a function based view this aggregate

"categories": models.Listing.objects.all().values('category').annotate(num_category=Count('category')).order_by('num_category'),

in the template I want to display the category’s name and num_category.

{{ listing.category.name }}

This doesn’t display anything, is this because it’s an aggregate?
Is there a way to display the name of the category?

Best,

Johanna

My first reaction is that this is caused by using the values clause in that query. Without seeing more information on the view and template, I’d suggest removing that values call so that your queryset contains the full object.

What are you supplying to the template in the context?

(We may need to see the complete view. Also, if that line from the template is in some kind of loop, it would be helpful to see the template as well.)

Thanks for your reply.

Removing the call to values resulted in a none aggregated list.

Reading the aggregation Cheat Sheet I found a better solution.

"categories": models.Category.objects.annotate(num_listings=Count('listing_category', filter=Q(listing_category__closed=False))).order_by('-num_listings')

A left join also giving me the categories with no listings yet.

Ok, there’s not enough here to diagnose this. I think we’re going to need to see the complete query, the context being used for the template, and a larger chunk of the template - if this particular variable being rendered is inside one or more loops.