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

查看:55
本文介绍了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天全站免登陆