模板中的django反向外键
django reverse foreignkey in template
嘿!
我有多个连接模型,想通过模板显示信息。
所有模型都通过外键连接,但我只能在一个方向上显示信息。
有谁知道如何反向显示两种方式?
我可以轻松获取'Survey'和'Certification'的信息,但无法获取'SurveyBga'和'Address'的信息。
感谢任何帮助! :)
# models.py
class Survey(models.Model):
survey_bga_id = models.ForeignKey(
SurveyBga,
on_delete=models.PROTECT,
related_name="experiment"
)
year = models.PositiveSmallIntegerField(
validators=[validate_year]
)
class Certification(models.Model):
survey_bga_yeardependent_id = models.ForeignKey(
Survey,
on_delete=models.PROTECT,
related_name="certification"
)
type_of_experience = models.BooleanField(
blank=True,
null = True
)
class Address(models.Model):
street = models.CharField(
max_length = 150,
blank = True,
)
class SurveyBga(Address):
internal_id = models.CharField(
unique = True,
max_length = 10
)
# views.py
def experiment_bga_view(request):
bga = Survey.objects.all()
context = {"bga": bga}
return render(request, 'app/template.html', context)
我试过了
{% for survey in bga %}
{% for plant in survey.experiment_set.all %}
{{plant.internal_id}}
{% endfor %}
{% endfor %}
{% for survey in bga %}
{% for plant in survey.experiment.all %}
{{plant.internal_id}}
{% endfor %}
{% endfor %}
{% for survey in bga %}
{{survey.experiment.internal_id}}
{% endfor %}
您使用 related_name 的方式有误。我是:
要从“调查”访问“SurveyBga”,只需执行以下操作:
{% for survey in bga %}
{{survey.survey_bga_id.internal_id}}
{% endfor %}
根据您的代码,您可以使用 related_name“实验”以相反的方式从“SurveyBga”访问“调查”。
surveybga = SurveyBga.objects.get(id=.....)
survey = surveybga.experiment
嘿!
我有多个连接模型,想通过模板显示信息。 所有模型都通过外键连接,但我只能在一个方向上显示信息。 有谁知道如何反向显示两种方式?
我可以轻松获取'Survey'和'Certification'的信息,但无法获取'SurveyBga'和'Address'的信息。
感谢任何帮助! :)
# models.py
class Survey(models.Model):
survey_bga_id = models.ForeignKey(
SurveyBga,
on_delete=models.PROTECT,
related_name="experiment"
)
year = models.PositiveSmallIntegerField(
validators=[validate_year]
)
class Certification(models.Model):
survey_bga_yeardependent_id = models.ForeignKey(
Survey,
on_delete=models.PROTECT,
related_name="certification"
)
type_of_experience = models.BooleanField(
blank=True,
null = True
)
class Address(models.Model):
street = models.CharField(
max_length = 150,
blank = True,
)
class SurveyBga(Address):
internal_id = models.CharField(
unique = True,
max_length = 10
)
# views.py
def experiment_bga_view(request):
bga = Survey.objects.all()
context = {"bga": bga}
return render(request, 'app/template.html', context)
我试过了
{% for survey in bga %}
{% for plant in survey.experiment_set.all %}
{{plant.internal_id}}
{% endfor %}
{% endfor %}
{% for survey in bga %}
{% for plant in survey.experiment.all %}
{{plant.internal_id}}
{% endfor %}
{% endfor %}
{% for survey in bga %}
{{survey.experiment.internal_id}}
{% endfor %}
您使用 related_name 的方式有误。我是:
要从“调查”访问“SurveyBga”,只需执行以下操作:
{% for survey in bga %}
{{survey.survey_bga_id.internal_id}}
{% endfor %}
根据您的代码,您可以使用 related_name“实验”以相反的方式从“SurveyBga”访问“调查”。
surveybga = SurveyBga.objects.get(id=.....)
survey = surveybga.experiment