我有这个型号:
class House(models.Model):
name = models.CharField()
class BedRoom(models.Model):
name = models.CharField()
class Catalog(models.Model):
name = models.CharField()
house = models.ForeignKey(House)
bedroom = models.ForeignKey(BedRoom)
at admin.py目录内联到House
class CatalogInline(admin.TabularInline):
model = Catalog
class HomeAdmin(admin.ModelAdmin):
inline = [CatalogInline]
然后我需要在房屋目录中获取卧室列表,在家里模型我有:
def bedrooms(self):
return self.catalog_set.all()
但是当我在模板中从视图中获取“房屋”时:
{% for house in houses %}
{% for h in house %}
<p>{{h.name}}</p>
{% endfor %}
{% endfor %}
我收到错误: 'Catalog'对象不可迭代
我做错了什么?
我应该以不同的方式定义模型吗?
答案 0 :(得分:2)
正如我所提到的,你似乎并没有真正调用bedrooms
方法。我猜(这只是猜测)你的意思是:
{% for house in houses %}
{% for h in house.bedrooms %}
<p>{{h.name}}</p>
{% endfor %}
{% endfor %}
bedrooms
方法毫无意义,因为您可以轻松地执行此操作:
{% for house in houses %}
{% for h in house.catalog_set.all %}
<p>{{h.name}}</p>
{% endfor %}
{% endfor %}