Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - Get the set of objects from Many To One relationship

Tags:

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.

like image 571
Aamu Avatar asked Nov 05 '13 22:11

Aamu


People also ask

How fetch data from many-to-many field in Django?

A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.

How does Django define many to one relationships?

To define a one to many relationship in Django models you use the ForeignKey data type on the model that has the many records (e.g. on the Item model).

How does Django handle many-to-many relationship?

Django will automatically generate a table to manage many-to-many relationships. You might need a custom “through” model. The most common use for this option is when you want to associate extra data with a many-to-many relationship.

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.


1 Answers

You are almost there. you should be using photo_set instead of image_set

>>>t_album.photo_set.all()  

i.e the lowercase modelname with _set

If you want the list of photos in 1 query,

photos = Photo.objects.filter(album__user__username='tika') 
like image 62
karthikr Avatar answered Sep 20 '22 18:09

karthikr