I have a model which is defined as shown which is acted upon a query and gets a list of objects that have to placed in appropriate cells of a table. Here is the relevant part of the code.
class Location(models.Model):
x=models.IntegerField(null=True)
y=models.IntegerField(null=True)
z=models.CharField(max_length=5,null=True)
def __unicode__(self):
return self.z
From this db i want retrieve all the objects and place them in a 2d-table with row and column defined by x,y of that object.If there is no object for certain (x,y) then that particular slot should be shown empty in the table.This is the view I wrote to meet those ends.
def gettable(request):
events=[]
for xdim in xrange(3):
xe=[]
for ydim in xrange(3):
object=[0]
object.append(Location.objects.filter(x=xdim,y=ydim))
xe.append(object[-1])
events.append(xe)
return render(request, 'scheduler/table.html', {'events':events})
Here is the html part of the code
<table border="1">
<th>Header 0</th>
<th>Header 1</th>
<th>Header 2</th>
{% for event in events %}
<tr>
{% for x in event %} <td>{{ x }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
I have to tackle multiple issues here.
1.My code for views is not at all elegant (which is bad since I know django offers lots of stuff to tackle such tasks) as I am defining variables specifically to loop through instead of taking those from the (x,y) values of database objects.
2.I get output in [<Location: 21>] format but I want it as '21'.
3.How do I introduce empty cells where there doesnot exist any object for given (x,y).
4.Please suggest any other way possible which can make my code simpler and general.