Search code examples
mysqldjango-modelsmysql-error-1242

Django subquery problem "Subquery returns more than 1 row"


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


Solution

  • 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 model City, you can get all Districts 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.