Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9045793
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T11:26:49+00:00 2026-06-16T11:26:49+00:00

I have the following annotation in a Django model manager I’d like to convert

  • 0

I have the following annotation in a Django model manager I’d like to convert to a SQLAlchemy ORM query:

annotations = {
        'review_count' : Count("cookbookreview", distinct=True), 
        'rating' : Avg("cookbookreview__rating")
    }
return self.model.objects.annotate(**annotations)

What I essentially need is each model object in the query to have review_count and rating attached to them as part of the initial query. I believe I can use column_property, but I would like to avoid this type of “calculated property” on the object, because I don’t want the property (expensive lookup) being done for each object when I access the property in a template.

What is the right way to approach this problem? Thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T11:26:50+00:00Added an answer on June 16, 2026 at 11:26 am

    So, for the sake of completeness and usefulness for others with this issue I present the following solution (which may or may not be the optimal way to solve this)

    sq_reviews = db_session.query(CookbookReview.cookbook_id, 
        func.avg(CookbookReview.rating).label('rating'),\
        func.count('*').label('review_count')).\
        group_by(CookbookReview.cookbook_id).subquery()
    
    object_list = db_session.query(
        Cookbook, sq_reviews.c.rating, sq_reviews.c.review_count).\
        outerjoin(sq_reviews, Cookbook.id==sq_reviews.c.cookbook_id).\
        order_by(Cookbook.name).limit(20)
    

    The key here is the concept of SQLAlchemy subqueries. If you think of each annotation in my original Django query as a subquery, the concept is easier to understand. It’s also worth noting that this query is quite speedy – many orders of magnitude swifter than it’s (more concise/magical) Django counterpart. Hopefully this helps others curious about this particular Django/SQLAlchemy query analog.

    Also keep in mind that you need to perform the actual annotation of the ORM objects yourself. A simple function like this called before sending the object list to your template will suffice:

    def process(query):
        for obj, rating, review_count in query:
            obj.rating = rating
            obj.review_count = review_count
            yield obj
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this model with the following data annotation because I want to handle
I have write following code to show bar plot annotation. Annotations are shown but
I have the following code and whichever service is created last works(so my annotations
I have the following regular expression in my data annotation: [RegularExpression(@test|test2|test3|test4-5, ErrorMessage = Please
We have the following classes @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) // optional annotation as this
I have the following code that works fine in my spring.xml... <beans:bean id=sessionFactory class=org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean>
I have the following Java annotation on a class (it's for a myBatis plugin):
I have the following configuration: @Aspect public class MyAspect { @Around(@annotation(SomeAnnotation)) public Object myMethod(ProceedingJoinPoint
I have the following code: - (MKAnnotationView *) mapView:(MKMapView *) mapView viewForAnnotation:(id ) annotation
Suppose I have the following XML (which is the embedding of TEI annotation scheme

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.