Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
Ordering queryset by filtered child objects

I have the following (simplified) data model, see visual representation below the post:

  • Articles, which have Attributes
  • Attributes refer by PK to a Type, which have a field code
  • Attributes have a field value
  • The value refers to the field uuid in another model called Record, which also has a field sorting_code

I now want to return a list of articles in a certain ordering, using pagination. I am using a default ViewSet for it. The pagination forces me to do the ordering in database, instead of later in Python. However, I cannot seem to find the correct ordering clause that orders these articles. What I need to do is:

  • Fetch the Attribute with a specific type
  • Look up the values in those Attributes in the Record table
  • Order the articles based by sorting_code

The following SQL query does the job (for all articles):

SELECT art.order_id, art.uuid, att.value, mdr.code, mdr.name, mdr.sorting_code
FROM ow_order_article art
INNER JOIN ow_order_attribute att ON att.article_id = art.uuid
INNER JOIN ow_masterdata_type mdt ON att.masterdata_type_id = mdt.uuid
INNER JOIN ow_masterdata_record mdr ON att.value = mdr.uuid
WHERE mdt.code = 'article_structure'
ORDER BY mdr.sorting_code, mdr.code

What would be the correct way to get this ordering in a queryset in Django?

Data model simplified

about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!