Please have a look at these models:
class Album(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=200)
pub_date = models.DateTimeField(default=datetime.now)
class Photo(models.Model):
album = models.ForeignKey(Album, default=3)
image = models.ImageField(upload_to=get_upload_file_name)
caption = models.CharField(max_length=200)
pub_date = models.DateTimeField(default=datetime.now)
How do I get the the set of photos for a particular album??? And how to get the Album from the photo instance itself?
I tried this:
# To get the set of photos from the user (tika) album:
>>>t = User.objects.get(username='tika')
>>>t_album = Album.objects.get(user=t)
>>>t_album
<Album: tika_album>
>>>t_album.image_set.all()
AttributeError: 'Album' Object has no attribute 'image_set'
Please guide me to the right direction. Thank you.
Even better, you can write, in
Photo
The
photos
will be the name of the reverse field fromAlbum
toPhoto
. If you don't define it, the reverse field will be namedphoto_set
.You then use
or
You are almost there. you should be using
photo_set
instead ofimage_set
i.e the lowercase modelname with
_set
If you want the list of photos in 1 query,