2👍
I would probably change the name of the parameter (in the view and in the urls.py) to something like country_name
, as country.pk
is usually configured to return the same as country.id
. And for the sake of convention I would change the name of the name field on the country to name
rather than Countryname
.
class Country(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
Then in your view, you can look up the CountryDiseases objects by the name
field on the related Country model:
def County_Details(request, country_name):
C_Details = CountryDiseases.objects.filter(country__name=country_name)
return render(request, 'DATAPLO/Country_Details.html', {'C_Details': C_Details})
Or if you want to look up the country first, as well as the details, because you may have other information stored on the country model, then you can change the CountryDiseases lookup to reference the Country object directly:
def County_Details(request, country_name):
country = Country.objects.get(name=country_name)
C_Details = CountryDiseases.objects.filter(country=country)
return render(request, 'DATAPLO/Country_Details.html', {'C_Details': C_Details})
PS if capitalisation is going to be an issue, such as with ‘india’ vs ‘India’, you can use the lookup:
.filter(country__name__iexact=country_name)
(for in the first code example) or.get(name__iexact=country_name)
(in the second, but there also you should ensure that you don’t have clashes when saving the objects, as you’re making a.get()
query).
Source:stackexchange.com