I'm trying to filter objects of model based on associated grandparent model. They are associated with each other through an intermediary parent model. Parent model is associated with grandparent through ContentType GenericForeignKey. How can I access all objects of target model sharing same Grandparent?
I tried to use GenericRelations on Grandparent but it did not work as it returns all the Parent Objects associated with that GrandParent Model. For that, I've to loop through querysets. Please check the code for details:
class State(models.Model):
name = models.CharField(max_length=25)
population = models.PositiveIntegerField()
class UnionTerritory(models.Model):
name = models.CharField(max_length=25)
population = models.PositiveIntegerField()
class District(models.Model):
name = models.CharField(max_length=25)
content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type','object_id')
population = models.PositiveIntegerField()
class Town(models.Model):
name = models.CharField(max_length=25)
district = models.ForeignKey(District,related_name='towns',on_delete=models.CASCADE)
population = models.PositiveIntegerField()
"""Here, District can be connected to State or UnionTerritory but town will always be part of district."""
Now, if I select any State or UnionTerritory Object; I want to have access to all towns under it. I want to filter all Town instances who share same State or UnionTerritory. Towns can be connected to different districts which belong to same state or same UnionTerritory. How can I access UnionTerritory or State associated with Town and then filter town objects accordingly. Is there any way to avoid looping through querysets to achieve this?