I know this is dumb but…
I have two model classes
class Gallery(models.Model):
name = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published', auto_now_add=True)
def __unicode__(self):
return self.name
class Image(models.Model):
gallery = models.ForeignKey(Gallery)
image = models.ImageField(upload_to='gallery/%Y/%m/%d')
caption = models.TextField(blank=True)
up_date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.caption
I want three types of query
- Get all the “Gallery” with one “Image” from that gallery
- Get all the image from a single gallery
third one I can handle get a specific image from a “Image”
I think I understand what you’re looking for.
Query #1
You want all galleries, along with a single image for each gallery. Since Django automatically allows you to access related objects you can accomplish this by simply retrieving all the galleries in your db.
select_related()automatically “follows” foreign-key relationships when it executes the query, which means later use of foreign-key relationships won’t require database queries.To get the first image from each gallery in your template, you would do this:
https://docs.djangoproject.com/en/dev/ref/models/querysets/
https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
Query #2
This actually works exactly the same as the previous query, but for only a single gallery.
In your template: