[英]Django - Follow a backward ForeignKey and then a ForeignKey (query)
我使用Django 1.9和Python 2.7。
我的应用程序有四个模型。 每个“行程”都是由访客选择的几个“步骤”组成的,这些步骤与“地点”相关,而“地点”可能具有多个相关的“图片”。
class Trip(models.Model):
title = models.CharField(max_length=140, blank=True)
class Step(models.Model):
theplace = models.ForeignKey(ThePlace)
trip = models.ForeignKey(Trip)
class ThePlace(models.Model):
name = models.CharField(max_length=200)
class Picture(models.Model):
file = models.ImageField(upload_to="pictures")
slug = models.SlugField(max_length=100, blank=True)
theplace = models.ForeignKey(ThePlace, null=True, blank=True)
我想使用现有的“ selectedtrip”查询集来检索与特定Trip相关的所有“ Picture”对象:
selectedtrip = Trip.objects.filter(author=request.user)[0]
pictures = selectedtrip.step_set.all().theplace.picture_set.all()
Django显示以下错误:“ AttributeError:'QuerySet'对象没有属性'theplace'”任何想法为何?
因为all()
返回一个queryset,它是项目的集合; theplace
是单个Step的属性,而不是集合的属性。
进行此类查询的方法是从要检索的类开始,并使用双下划线语法遵循查询中的关系。 所以:
Picture.objects.filter(theplace__step__trip=selectedtrip)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.