Django 子查询问题“子查询返回超过 1 行”
我有三个相关的模型,例如
class City(models.Model):
name = models.CharField(max_length=200, blank=False)
country = models.ForeignKey(Country,unique=False,null=False)
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
class County(models.Model):
name = models.CharField(max_length=500, blank=False)
city = models.ForeignKey(City,unique=False,null=False)
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
class District(models.Model):
name = models.CharField(max_length=500, blank=False)
county = models.ForeignKey(County,unique=False,null=False)
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
我想做的是获取指定城市的所有Districts
。 我尝试过:
District.objects.all().filter(county = County.objects.all().filter(city=City.objects.filter(id=4)))
但是,它给出了类似 OperationalError: (1242, 'Subquery returns more more than 1 row')
的错误,
您能给我任何想法如何在 django 中实现此查询吗?
谢谢
I have three related models like
class City(models.Model):
name = models.CharField(max_length=200, blank=False)
country = models.ForeignKey(Country,unique=False,null=False)
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
class County(models.Model):
name = models.CharField(max_length=500, blank=False)
city = models.ForeignKey(City,unique=False,null=False)
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
class District(models.Model):
name = models.CharField(max_length=500, blank=False)
county = models.ForeignKey(County,unique=False,null=False)
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
What I'd like to do is getting all the Districts
for a specified city.
I tried :
District.objects.all().filter(county = County.objects.all().filter(city=City.objects.filter(id=4)))
However, it gives error like OperationalError: (1242, 'Subquery returns more than 1 row')
Can you give me any idea how I can achive this query in django ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道为什么你这样做会让事情变得复杂。您可以这样做:
对于模型
City
的给定实例city
,您可以通过这种方式获取所有Districts
:District.objects.filter(county__city=city)
您可能需要浏览 Django 文档中名为 跨越关系的查找,因为它解释了如何实现类似的查找查询。
I'm not sure why you're complicating things by doing them that way. You could get away with something along the lines of:
For a given instance
city
of the modelCity
, you can get allDistricts
in this way:District.objects.filter(county__city=city)
You may want to go through this section on the Django documentation called Lookups that span relationships as it explains how you can achieve similar lookup queries.