如何通过ContentType GenericForeignKey访问与目标模型关联的祖父母模型的objects?

How to access objects of grandparent model associated with target model through ContentType GenericForeignKey?

我正在尝试根据关联的 grandparent 模型过滤 objects 模型。它们通过中介 parent 模型相互关联。 Parent 模型通过 ContentType GenericForeignKey 与 grandparent 相关联。如何访问所有 objects 共享相同 Grandparent 的目标模型?

我尝试在 Grandparent 上使用 GenericRelations,但它不起作用,因为它 returns 所有与该 Grand[=23= 关联的 Parent Object ] 模型。为此,我必须遍历查询集。详情请查看代码:

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."""

现在,如果我 select 任何州或联邦领地 Object;我想访问它下面的所有城镇。我想过滤所有共享同一个 State 或 UnionTerritory 的 Town 实例。城镇可以连接到属于同一州或同一联盟领土的不同地区。如何访问与 Town 关联的 UnionTerritory 或 State,然后相应地过滤城镇 objects。 有什么方法可以避免循环查询集来实现这一点?

几天前我得到了上述问题的答案。诀窍在于将 GenericRelation() 包含在 ContentType Foreignkey 可能指向的 parent 模型中。 我在 Grandparent 模型上使用了 GenericRelation。代码如下:

#in models.py:

from django.contrib.contenttypes.fields import GenericRelation

class State(models.Model):
    name = models.CharField(max_length=25)
    population = models.PositiveIntegerField()
    **districts = GenericRelation(District)**

"""this GenericRelation allows us to access all districts under particular state using
state.districts.all() query in case of genericforeignkey reverse relation.
**note:** You can use GenericRelation(**'***module_name*.District**'**) to avoid any circular
import error if District Model lies in another module as it was in my case."""

# same can be done with UnionTerritory Model

class UnionTerritory(models.Model):
    name = models.CharField(max_length=25)
    population = models.PositiveIntegerField()
    districts = GenericRelation(District) 

#Other models required no change.

真正的窍门在 views.py。我不确定这是否可以称为正确的解决方案或 work-around 但它确实给出了预期的结果。假设,我想访问特定州的所有城镇列表,代码如下:

#in views.py,
from django.shortcuts import get_object_or_404

def state_towns(request,pk):
    target_state = get_object_or_404(State,pk=pk)
    districts_under_state = target_state.districts.all()
    towns_under_state = Town.objects.filter(name__in=districts_under_state).all()

"""first line gives us the state for which we want to retrieve list of towns. 
Second line will give us all the districts under that state and third line 
will finally filter out all towns those fall under those districts. 
Ultimately, giving us all the towns under target state."""

伙计们,我对django不是很有经验。所以,如果这段代码有任何错误或者是否有更好的实现方法,请通知我。那些像我一样有同样问题的人,这可以成为我们的解决方案,直到出现更好的解决方案。谢谢