Home > Enterprise >  django reverse foreignkey in template
django reverse foreignkey in template

Time:03-04

Hej!

I have multiple connected models and want to display the info via a template. All models are connected via foreignkeys, but I only can display the info in one direction. Does anyone know how to reverse to show both ways?

I can easily get the information of 'Survey' and 'Certification' but can't get to 'SurveyBga' and 'Address'.

Any help is appreciated! :)

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

I tried

{% 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 %}

CodePudding user response:

You are using related_name in the wrong way. I meen:

To access to "SurveyBga" from "Survey", just do:

{% for survey in bga %}
    {{survey.survey_bga_id.internal_id}}
{% endfor %}

According to your code, you can use the related_name "experiment" to access to "Survey" from "SurveyBga", in the opposite way.

surveybga = SurveyBga.objects.get(id=.....)
survey = surveybga.experiment
  • Related