我正在处理我的第一个 Django 站点,到目前为止一切顺利。我现在面临从数据库获取一些信息的挑战。我的模型如下所示:
class Countries(models.Model):
country = models.CharField(max_length=100)
def __unicode__(self):
return self.country
class OrganisationTypes(models.Model):
organisation_type = models.CharField(max_length=100)
def __unicode__(self):
return self.organisation_type
class Organisations(models.Model):
organisation_name = models.CharField(max_length=200)
organisation_type = models.ForeignKey(OrganisationTypes)
country_of_origin = models.ForeignKey(Countries)
def __unicode__(self):
return self.organisation_name
class Locations(models.Model):
organisation = models.ForeignKey(Organisations)
country_of_location = models.ForeignKey(Countries)
tel_nr = models.CharField(max_length=15)
address = models.CharField(max_length=100)
def __unicode__(self):
return '%s - %s - %s - %s' % (self.organisation, self.country_of_location, self.tel_nr, self.address)
我现在想显示我想显示的位置列表organisation_name
和 country_of_origin。为此,我编写了以下函数:
def organisation_locations(requests, organisation_id):
org = Organisations.objects.get(id=organisation_id)
location_list = Locations.objects.filter(organisation=organisation_id).order_by('country_of_location')
output = '<br />'.join([str(loc.organisation)+' from '+str(org.country_of_origin) for loc in location_list])
return HttpResponse(output)
这可以正常工作,但似乎不是正确的方法。由于 Location 表在 Organizations 表中有一个外键,而在 Country 表中有一个外键,我有一种模糊的感觉,Django 可以在一个“查询”或查找中做到这一点。
我的这种感觉是正确的,还是我的方式确实是正确的方式?欢迎所有提示!