Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 921
brsbilgic Avatar asked May 01 '26 03:05

brsbilgic


1 Answers

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.

like image 150
ayaz Avatar answered May 02 '26 22:05

ayaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!