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

ぐ巨炮叔叔 提交于 2020-01-01 02:07:50

问题


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.


回答1:


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')



回答2:


Even better, you can write, in Photo

album = models.ForeignKey(Album, related_name='photos', default=3)

The photos will be the name of the reverse field from Album to Photo. If you don't define it, the reverse field will be named photo_set.

You then use

t_album.photos.all()  # only if you've defined the `related_name` argument to 'photos'

or

t_album.photo_set.all()


来源:https://stackoverflow.com/questions/19799955/django-get-the-set-of-objects-from-many-to-one-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!