Django: one template for different lists of objects
my model is basically a chain of objects linked by a foreign key:
class Object1(object):
object1_id = models.AutoField()
object1_name = models.CharField()
class Object2(object):
object2_id = models.AutoField()
object2_name = models.CharField()
object1 = models.ForeignKey(Object1)
class Object3(object):
object3_id =开发者_开发知识库 models.AutoField()
object3_name = models.CharField()
object2 = models.ForeignKey(Object2)
I want to able to display lists of objects per class, each line being a link to the list of the son objects. If an id is given, the list should only contain the objects whose parent have the given id. So in my view i have functions like these:
def object1(request):
liste = Object1.objects.all()
return render_to_response('list.html', {'list' : list, 'link' : link})
def object2(request, id):
if id == 0:
list = Object2.objects.all()
link = "object3"
render_to_response('list.html', {'list' : list, 'link' : link})
else:
liste = Object2.objects.filter(object1 = id)
return render_to_response('list.html', {'list':list, 'link':link})
the problem is that i don't know how to create a single template able to display these list:
{% for ele in list %}
<li><a href="/{{link}}/{{ele.id}}/">{{ele.name}}</a></li>
{% endfor %}
doesn't work because the id and te name of the object is different in each case. By the way if anybody has an idea of how to create one view to do the job, it would be appreciated. Thanks
Is there any reason why you need to have different names for the same attributes in different models? It seems unnecessary. In fact, I wonder why you need different models at all.
If you really do need to do this, I suggest you add properties to each of the models to get their name and id values:
@property
def name(self):
return self.object1_name
and so on - now you can simply do {{ ele.name }}
in the template.
精彩评论