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 6967465
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T16:19:31+00:00 2026-05-27T16:19:31+00:00

I have a Django query and some Python code that I’m trying to optimize

  • 0

I have a Django query and some Python code that I’m trying to optimize because 1) it’s ugly and it’s not as performant as some SQL I could use to write it, and 2) because the hierarchical regrouping of the data looks messy to me.

So,
1. Is it possible to improve this to be a single query?
2. How can I improve my Python code to be more Pythonic?

Background

This is for a photo gallery system. The particular view is attempting to display the thumbnails for all photos in a gallery. Each photo is statically sized several times to avoid dynamic resizing, and I would like to also retrieve the URLs and “Size Type” (e.g. Thumbnail, Medium, Large) of each sizing so that I can Lightbox the alternate sizes without hitting the database again.

Entities

I have 5 models that are of relevance:

class Gallery(models.Model):
    Photos = models.ManyToManyField('Photo', through = 'GalleryPhoto', blank = True, null = True)

class GalleryPhoto(models.Model):
    Gallery = models.ForeignKey('Gallery')
    Photo = models.ForeignKey('Photo')
    Order = models.PositiveIntegerField(default = 1)

class Photo(models.Model):
    GUID = models.CharField(max_length = 32)

class PhotoSize(models.Model):
    Photo = models.ForeignKey('Photo')
    PhotoSizing = models.ForeignKey('PhotoSizing')
    PhotoURL = models.CharField(max_length = 1000)

class PhotoSizing(models.Model):
    SizeName = models.CharField(max_length = 20)
    Width = models.IntegerField(default = 0, null = True, blank = True)
    Height = models.IntegerField(default = 0, null = True, blank = True)
    Type = models.CharField(max_length = 10, null = True, blank = True)

So, the rough idea is that I would like to get all Photos in a Gallery through GalleryPhoto, and for each Photo, I want to get all the PhotoSizes, and I would like to be able to loop through and access all this data through a dictionary.

A rough sketch of the SQL might look like this:

Select PhotoSize.PhotoURL
From PhotoSize
Inner Join Photo On Photo.id = PhotoSize.Photo_id
Inner Join GalleryPhoto On GalleryPhoto.Photo_id = Photo.id
Inner Join Gallery On Gallery.id = GalleryPhoto.Gallery_id
Where Gallery.id = 5
Order By GalleryPhoto.Order Asc

I would like to turn this into a list that has a schema like this:

(
    photo: {
        'guid': 'abcdefg',
        'sizes': {
            'Thumbnail': 'http://mysite/image1_thumb.jpg',
            'Large': 'http://mysite/image1_full.jpg',
            more sizes...
        }
    },
    more photos...
)

I currently have the following Python code (it doesn’t exactly mimic the schema above, but it’ll do for an example).

gallery_photos = [(photo.Photo_id, photo.Order) for photo in GalleryPhoto.objects.filter(Gallery = gallery)]
photo_list = list(PhotoSize.objects.select_related('Photo', 'PhotoSizing').filter(Photo__id__in=[gallery_photo[0] for gallery_photo in gallery_photos]))

photos = {}
for photo in photo_list:
    order = 1
    for gallery_photo in gallery_photos:
        if gallery_photo[0] == photo.Photo.id:
            order = gallery_photo[1] //this gets the order column value

            guid = photo.Photo.GUID
            if not guid in photos:
                photos[guid] = { 'Photo': photo.Photo, 'Thumbnail': None, 'Sizes': [], 'Order': order }

            photos[guid]['Sizes'].append(photo)

    sorted_photos = sorted(photos.values(), key=operator.itemgetter('Order'))

The Actual Question, Part 1

So, my question is first of all whether I can do my many-to-many query better so that I don’t have to do the double query for both gallery_photos and photo_list.

The Actual Question, Part 2

I look at this code and I’m not too thrilled with the way it looks. I sure hope there’s a better way to group up a hierarchical queryset result by a column name into a dictionary. Is there?

  • 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-05-27T16:19:31+00:00Added an answer on May 27, 2026 at 4:19 pm

    When you have sql query, that is hard to write using orm – you can use postgresql views. Not sure about mysql. In this case you will have:

    Raw SQL like:

    CREATE VIEW photo_urls AS
    Select
    photo.id, --pseudo primary key for django mapper
    Gallery.id as gallery_id, 
    PhotoSize.PhotoURL as photo_url
    From PhotoSize
    Inner Join Photo On Photo.id = PhotoSize.Photo_id
    Inner Join GalleryPhoto On GalleryPhoto.Photo_id = Photo.id
    Inner Join Gallery On Gallery.id = GalleryPhoto.Gallery_id
    Order By GalleryPhoto.Order Asc
    

    Django model like:

    class PhotoUrls(models.Model):
        class Meta: 
             managed = False 
             db_table = 'photo_urls'
        gallery_id = models.IntegerField()
        photo_url = models.CharField()
    

    ORM Queryset like:

    PhotoUrls.objects.filter(gallery_id=5)
    

    Hope it will help.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a query that I'm trying to figure the django way of doing
I have a query in Django that is resulting in unique rows but some
I have a python function that scrapes some data from a few different websites
I was trying to setup django . I do have Django-1.1-alpha-1. I was trying
Newbie question. I have Django models that look like this: class Video(models.Model): uploaded_by =
I have a django project, but for some reason basic jquery isn't working. <html>
Hi I have some problems that has been bothering me for a week. I
Hi Everyone I m dealing with some serious issue in django-admin.I have created models
I have a simple view in Django: @render_to('episode_list.html') def list_episodes(request, season): query = Episode.objects.filter(season=season)
I have some rather long (~150 character) django queries. What's the preferred way to

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.