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

时间:2018-12-28 03:13:58

标签: django django-queryset django-contenttypes django-generic-relations

我正在尝试根据关联的祖父母模型过滤模型的对象。它们通过中介父模型相互关联。父模型通过ContentType GenericForeignKey与祖父母关联。如何访问共享同一祖父母的目标模型的所有对象?

我尝试在Grandparent上使用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对象;我想访问它下面的所有城镇。我想过滤共享相同州或联盟领土的所有Town实例。城镇可以连接到属于同一州或同一UnionTerritory的不同地区。如何访问与Town关联的UnionTerritory或State,然后相应地过滤Town对象。 有什么方法可以避免循环遍历查询集来实现这一目标?

1 个答案:

答案 0 :(得分:0)

几天前,我得到了上述问题的答案。诀窍在于在ContentType外键可能指向的父模型中包含GenericRelation()。 我在祖父母模型上使用了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中。我不确定这是否可以称为适当的解决方案或解决方法,但是确实可以达到预期的结果。假设我要访问特定州所有城镇的列表,代码如下:

#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不太了解。因此,如果此代码有任何错误或有更好的实现方法,请通知我。像我一样有同样问题的人,直到更好的解决方案来临,这是我们的解决方案。谢谢。

相关问题