0

我正在尝试根据关联的祖父母模型过滤模型对象。它们通过中间父模型相互关联。父模型通过 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,然后相应地过滤城镇对象。有什么方法可以避免通过查询集循环来实现这一点?

4

1 回答 1

0

几天前,我得到了上述问题的答案。诀窍在于将 GenericRelation() 包含在 ContentType Foreignkey 可能指向的父模型中。我在祖父母模型上使用了 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 不是很有经验。因此,如果此代码有任何错误或是否有更好的方法来实现,请通知我。像我一样有同样问题的人,这可以作为我们的解决方案,直到更好的解决方案出现。谢谢。

于 2019-01-08T06:51:48.480 回答