django - 从多对一关系中获取对象集 [英] django - Get the set of objects from Many To One relationship

查看:30
本文介绍了django - 从多对一关系中获取对象集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看一下这些模型:

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?

我试过了:

# 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.

推荐答案

您就快到了.你应该使用 photo_set 而不是 image_set

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

>>>t_album.photo_set.all() 

即带有 _set 的小写模型名称

i.e the lowercase modelname with _set

如果您想要 1 个查询中的照片列表,

If you want the list of photos in 1 query,

photos = Photo.objects.filter(album__user__username='tika')

这篇关于django - 从多对一关系中获取对象集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆