我正在尝试根据关联的祖父母模型过滤模型对象。它们通过中间父模型相互关联。父模型通过 ContentType GenericForeignKey 与祖父关联。如何访问共享同一祖父母的目标模型的所有对象?
我尝试在祖父母上使用 GenericRelations,但它不起作用,因为它返回与该 GrandParent 模型关联的所有父对象。为此,我必须遍历查询集。详情请查看代码:
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."""
现在,如果我选择任何 State 或 UnionTerritory 对象;我想访问它下的所有城镇。我想过滤所有共享相同州或 UnionTerritory 的 Town 实例。城镇可以连接到属于同一州或同一UnionTerritory的不同地区。如何访问与 Town 关联的 UnionTerritory 或 State,然后相应地过滤城镇对象。有什么方法可以避免通过查询集循环来实现这一点?