我想显示属于每个公寓的房间列表,条件是每个公寓都有多个房间,逻辑上每个房间属于一个公寓,型号如下:
models.py
class apartement(models.Model):
user = models.OneToOneField(User,related_name='user')
name = models.CharField(default=0)
def __unicode__(self):
return u'%s' % self.user
class room(models.Model):
apartement = models.ForeignKey(apartement)
type = models.CharField(max_length=256)
capacity = models.IntegerField()
def __unicode__(self):
return u'%s' % (self.type)
view.py
apartement1 = apartement.objects.filter(user=request.user)
room1 = room.objects.select_related()
response['room1']=room1
template.py
{% for r in room1 %}
<td>{{ r.type }}</td>
<td> {{r.capacity}}</td>
{% endfor %}
它没有显示我想要的内容,我认为代码本身存在问题,有人可以帮助我。?
答案 0 :(得分:1)
您应该将apartement
的外键添加到room
模型中:
class room(models.Model):
apartement = models.ForeignKey(apartement)
type = models.CharField(max_length=256)
capacity = models.IntegerField()
def __unicode__(self):
return u'%s' % (self.type)
然后获取一个房间列表:
apartements = apartement.objects.get(user=request.user)
rooms = apartements.room_set.all()
模板:
{% for r in rooms %}
<td>{{ r.type }}</td>
<td>{{ r.capacity }}</td>
{% endfor %}
编辑:如果您不需要获取apartement
个实例,则可以使用此代码获取相同的房间列表:
rooms = room.objects.filter(apartement__user=request.user)