我正在尝试根据关联的祖父母模型过滤模型的对象。它们通过一个中间的父模型相互关联。父模型通过ContentType GenericForeignKey与祖模型关联。如何访问共享同一个祖辈的目标模型的所有对象?
我试图在祖父母上使用GenericRelations,但它不起作用,因为它返回与该Grandparent模型关联的所有父对象。为此,我必须遍历querysets。请检查代码以了解详细信息:
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."""现在,如果我选择任何州或UnionTerritory对象,我希望能够访问它下面的所有城镇。我想要过滤所有共享相同州或UnionTerritory的城市实例。城镇可以连接到属于同一州或同一UnionTerritory的不同地区。如何访问与城镇关联的UnionTerritory或州,然后相应地过滤城镇对象。有什么方法可以避免通过查询集循环来实现这一点吗?
发布于 2019-01-08 14:51:48
几天前,我得到了上述问题的答案。诀窍在于将GenericRelation()包含在ContentType外键可能指向的父模型中。我在祖父母模型上使用了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."""伙计们,我对姜戈不是很有经验。所以,如果这段代码中有任何错误,或者有没有更好的实现方法,请告诉我。那些像我一样有同样问题的人,这可以是我们的解决方案,直到更好的解决方案出现。谢谢。
https://stackoverflow.com/questions/53953283
复制相似问题