简体   繁体   English

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

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

I'm trying to filter objects of model based on associated grandparent model. 我试图基于关联的祖父母模型过滤模型的对象。 They are associated with each other through an intermediary parent model. 它们通过中介父模型相互关联。 Parent model is associated with grandparent through ContentType GenericForeignKey. 父模型通过ContentType GenericForeignKey与祖父母关联。 How can I access all objects of target model sharing same Grandparent? 如何访问共享同一祖父母的目标模型的所有对象?

I tried to use GenericRelations on Grandparent but it did not work as it returns all the Parent Objects associated with that GrandParent Model. 我尝试在Grandparent上使用GenericRelations,但由于它返回了与该GrandParent模型相关的所有父对象,因此无法正常工作。 For that, I've to loop through querysets. 为此,我必须遍历查询集。 Please check the code for details: 请检查代码以获取详细信息:

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

Now, if I select any State or UnionTerritory Object; 现在,如果我选择任何State或UnionTerritory对象; I want to have access to all towns under it. 我想访问它下面的所有城镇。 I want to filter all Town instances who share same State or UnionTerritory. 我想过滤共享相同州或联盟领土的所有Town实例。 Towns can be connected to different districts which belong to same state or same UnionTerritory. 城镇可以连接到属于同一州或同一UnionTerritory的不同地区。 How can I access UnionTerritory or State associated with Town and then filter town objects accordingly. 如何访问与Town关联的UnionTerritory或State,然后相应地过滤Town对象。 Is there any way to avoid looping through querysets to achieve this? 有什么方法可以避免循环查询集来实现这一点?

I got an answer for above question, few days back. 几天前,我得到了上述问题的答案。 The trick lies in including GenericRelation() in parent model to which ContentType Foreignkey may possibly point. 诀窍在于在ContentType外键可能指向的父模型中包含GenericRelation()。 I used GenericRelation on Grandparent model. 我在祖父母模型上使用了GenericRelation。 The code goes like this: 代码如下:

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

The real trick goes in views.py. 真正的把戏在views.py中。 I'm not sure if this can be called as proper solution or work-around but it does give the intended results. 我不确定这是否可以称为适当的解决方案或解决方法,但是确实可以达到预期的结果。 Assume, I want to access list of all towns in specific state, the code goes like this: 假设我要访问特定州所有城镇的列表,代码如下所示:

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

Guys, I am not very experienced in django. 伙计们,我对Django的了解不是很丰富。 So, please inform me if there is any mistake in this code or if there is a better way to implement this. 因此,如果此代码有任何错误或有更好的实现方法,请通知我。 Those who have same problem like me, this can be our solution till better one comes. 像我一样有同样问题的人,直到更好的解决方案来临,这是我们的解决方案。 Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM