Home > Software design >  Django display several foreign key values in template
Django display several foreign key values in template

Time:12-19

I have tried dozens of solutions on her to solve this but nothing seems to be working as expected. I'm trying to show a list of Facilites which are connected with several Foreign Keys to additonal models. (FacilityAddress, FacilityInspectionInfo and FacilityComplaints). I can show the facility names but i cannot show the data of the models within the foreign key models like FacilityAddress for example:

Model

class Facility(models.Model):
    UUID = models.CharField(max_length=150, null=True, blank=True)
    Name = models.CharField(max_length=50, null=True, blank=True)
    admin_uid = models.OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL)
    IssuedNumber = models.CharField(max_length=20, null=True, blank=True)
    mainimage = models.ImageField(null=True, blank=True)
    Capacity = models.IntegerField(null=True, blank=True)
    Licensee = models.CharField(max_length=50, null=True, blank=True)
    Email = models.EmailField(max_length=30, null=True, blank=True)
    AdministratorName = models.CharField(max_length=30, null=True, blank=True)
    Status = models.CharField(max_length=10, null=True, blank=True)
    TelephoneNumber = models.CharField(max_length=20, null=True, blank=True)
    ClosedTimestamp = models.IntegerField(null=True, blank=True)
    MostRecentLicenseTimestamp = models.IntegerField(null=True, blank=True)

    class Meta:
        verbose_name_plural = "facilities"

    def __str__(self):
        return self.Name


class FacilityAddress(models.Model):
    PrimaryAddress = models.CharField(max_length=50, null=True, blank=True)
    SecondaryAddress = models.CharField(max_length=50, null=True, blank=True)
    City = models.CharField(max_length=50, null=True, blank=True)
    RegionOrState = models.CharField(max_length=30, null=True, blank=True)
    PostalCode = models.CharField(max_length=20, null=True, blank=True)
    Geolocation = models.CharField(max_length=20, null=True, blank=True)
    AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE)

    class Meta:
        verbose_name_plural = "facility addresses"

    
    def __str__(self):
        return f"{self.PrimaryAddress} {self.City}"


class FacilityInspectionInfo(models.Model):
    ComplaintRelatedVisits = models.IntegerField(null=True, blank=True)
    InspectionRelatedVisits = models.IntegerField(null=True, blank=True)
    NumberOfVisits = models.IntegerField(null=True, blank=True)
    LastVisitTimestamp = models.IntegerField(null=True, blank=True)
    InspectionInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE)

    class Meta:
        verbose_name_plural = "facility inspection infos"

    def __str__(self):
        return self.InspectionInfo.Name


class FacilityComplaints(models.Model):
    ComplaintsTypeA = models.IntegerField(null=True, blank=True)
    ComplaintsTypeB = models.IntegerField(null=True, blank=True)
    SubstantiatedAllegations = models.IntegerField(null=True, blank=True)
    TotalAllegations = models.IntegerField(null=True, blank=True)
    Complaints = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE)

    class Meta:
        verbose_name_plural = "facility complaints"

    def __str__(self):
        return self.Complaints.Name

View

class FacListView(LoginRequiredMixin, generic.ListView):
    template_name = "facilities/facilities_page.html"
    context_object_name = "facilities"
    queryset = Facility.objects.all()

    def get_context_data(self, **kwargs):
        context = super(FacListView, self).get_context_data(**kwargs)
        context.update({
            "facilityaddress": FacilityAddress.objects.all()
        })
        return context

Template


{% for facility in facilities %}

    {{ facility.Name }} <br>
    {{ facility.TelephoneNumber }}
    {{ facilityaddress.facility.PrimaryAddress }}

{% endfor %}

CodePudding user response:

Since facility to facility relation is a reverse foreign key you can make use of the RelatedManager

Give this a try

Add a related name to AddressInfo field of FacilityAddress model

 AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa')

then in your template

{% for facility in facilities %}

    {{ facility.Name }} <br>
    {{ facility.TelephoneNumber }}

    {% for address in facility.fa.all %} <!-- related name-->
        {{address.PrimaryAddress }}
    {% endfor %}

{% endfor %}

that should work

  • Related