I have several models that I need to do reverse lookups in, then somehow chain the querysets together.
I got 3 models, (1) designers create (2) projects, and projects contain (3) uploaded images.
Models
class Designer(models.Model):
...
class Project(models.Model):
designer = models.ForeignKey('Designer')
class UploadedImage(models.Model):
project = models.ForeignKey('Project')
So a designer opens up his page and wants to see all his projects and some images associated with his projects, I could do something like,
d = Designer.objects.get(id=2)
projects = d.project_set.all()
But then with images, I gotta do this thing many many times, each time hitting the database.
images = []
for p in projects:
images.append(p.uploadedimage_set.all())
Now we have another problem, which is how do I connect images
and projects
?? I could do something stupid by building up a dictionary like this,
images = []
for p in projects:
images.append( { p.id : p.uploadedimage_set.all() } )
Then when I iterate through projects
, I could just use the id
to figure out which images are associated with which project.
Isn't there something a lot more elegant that'll allow me to,
- Hit the database just once
- Allow me to do something that'll look like
d.projects[0].images[0]
??? Instead of building up some sort of a stupid custom dictionary??? Does Django have some sort of queryset building tool or whatever?
Thanks!!