'Django View that shows related model context
I'm learning and I'm struggling to create a Django view that displays a Company Detail model, but also can show the associated location names that are located in child FK models to the Company.
What I've tried includes these models:
class Company(models.Model):
company_name = models.CharField(max_length=100, unique=True)
street = models.CharField('Street', max_length=100, null=True, blank=True)
city = models.CharField('City', max_length=100, null=True, blank=True)
province = models.CharField('Province/State', max_length=100, null=True, blank=True)
code = models.CharField('Postal/Zip Code', max_length=100, null=True, blank=True)
company_comments = models.TextField('Comments', max_length=350, null=True, blank=True)
class Region(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE)
region_name = models.CharField(max_length=100)
description = models.TextField(blank=True)
def __str__(self):
return self.region_name
class District(models.Model):
region = models.ForeignKey(Region, on_delete=models.CASCADE)
district_name = models.CharField(max_length=100)
description = models.TextField(blank=True)
dictrict_ops_leadership = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.district_name
My view looks like:
class CompanyDetailView(DetailView):
model = Company
template_name = 'main/company_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['region'] = Region.objects.all()
context['district'] = District.objects.all()
return context
I want to call **all instances of Region and District** for the **single instance of Company.**
With my HTML tags as : <p>{{ region }}{{ district }}</p>
It just returns a list of query's of all Region and District instances:
<QuerySet [<Region: RegionA>, <Region: RegionB>]>
<QuerySet [<District: DistrictA>, <District: DistrictB>]>
Any help would be GREATLY appreciated.
Thanks
Solution 1:[1]
Region.objects.filter(company__company_name = 'Your Company Name')
District.objects.filter(company__company_name = 'Your Company Name')
This will give You to the Region and District they related to the Your Comapany Name
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tanveer Ahmad |
