Я получил ответ на вышеуказанный вопрос, несколько дней назад.Хитрость заключается в том, чтобы включить GenericRelation () в родительскую модель, на которую ContentType Foreignkey может указывать.Я использовал GenericRelation для модели Grandparent.Код выглядит так:
#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.Поэтому, пожалуйста, сообщите мне, если есть какая-либо ошибка в этом коде или есть лучший способ реализовать это.Те, у кого такая же проблема, как и я, это может быть нашим решением, пока не придет лучшее.Спасибо.