我正在尝试在django模板中访问数据库表,但是我不知道使用外键从表切换到另一个的正确语法。 请注意,我的视图包含一个模型,而我试图使用外键访问其他模型。
我尝试使用“。”从表切换到另一个,但这不起作用。
那么,如何从事故中访问“位置”,“市政府”,“政府”和“地区”表? (在模板中)
class Accidents(models.Model):
id_acc = models.CharField(db_column='ID_Acc', primary_key=True, max_length=64) # Field name made lowercase.
id_loc = models.ForeignKey('Locations', db_column='ID_Loc') # Field name made lowercase.
date_acc = models.DateTimeField(db_column='Date_Acc') # Field name made lowercase.
simple_history = HistoricalRecords()
def __unicode__(self):
return '%s' % (self.id_acc)
class Meta:
db_table = 'accidents'
class District(models.Model):
id_d = models.IntegerField(db_column='ID_D', primary_key=True) # Field name made lowercase.
id_gov = models.ForeignKey('Governorate', db_column='ID_Gov') # Field name made lowercase.
name_d = models.TextField(db_column='Name_D') # Field name made lowercase.
class Meta:
db_table = 'district'
def __str__(self):
return self.name_d
class Governorate(models.Model):
id_gov = models.IntegerField(db_column='ID_Gov', primary_key=True) # Field name made lowercase.
name_gov = models.TextField(db_column='Name_Gov') # Field name made lowercase.
class Meta:
db_table = 'governorate'
def __str__(self):
return self.name_gov
class Locations(models.Model):
id_loc = models.AutoField(db_column='ID_Loc', primary_key=True) # Field name made lowercase.
id_mun = models.ForeignKey('Municipality', db_column='ID_Mun' ,default='null') # Field name made lowercase.
lat_loc = models.FloatField(db_column='Lat_Loc') # Field name made lowercase.
lon_loc = models.FloatField(db_column='Lon_Loc') # Field name made lowercase.
name_loc = models.TextField(db_column='Name_Loc') # Field name made lowercase.
class Meta:
db_table = 'locations'
def __str__(self):
return self.name_loc
def __unicode__(self):
return '%s' % (self.name_loc)
class Municipality(models.Model):
id_m = models.IntegerField(db_column='ID_M', primary_key=True) # Field name made lowercase.
id_d = models.ForeignKey(District, db_column='ID_D', blank=True, null=True) # Field name made lowercase.
name_m = models.CharField(db_column='Name_M', max_length=75, blank=True, null=True) # Field name made lowercase.
objects = models.GeoManager()
class Meta:
db_table = 'municipality'
#def __str__(self):
# return self.id_m
def __unicode__(self):
return '%s' % (self.name_m)
class MuniAccidentListView(ListView):
model= Accidents
context_object_name = 'accidents'
template_name = '...../plot_muni.html'
var stri = "{% for event in accidents %}{{event.date_acc}} {{event.id_loc.lat_loc}} {{event.id_loc.lon_loc}} {% endfor %}";
var strin = "{% for event in accidents %}{{event.date_acc}} {{event.id_loc.name_loc}} {% endfor %}";
var dis = "{% for event in accidents %}{{event.id_loc.id_mun.id_d.name_d}} {% endfor %}";