A student wanted to join 2 tables and display the results but he was not making any headway and couldn't figure out what was wrong with his code. After some debugging via printing to the console, I realised that he was not getting any data and that's why nothing was being displayed on his template. And there was a simple reason for this, his model was not set up to allow such a query. He was joining a table that had no foreign keys to various other tables that were linked to each other rather than to the first table.
class Players(models.Model):
PlayerName = models.CharField(max_length=100)
PlayerAddress = models.CharField(max_length=100)
PlayerEmailAddress = models.CharField(max_length=100)
PlayerPhoneNumber = models.IntegerField()
TeamID = models.ForeignKey(Team, on_delete=models.CASCADE)
Coach = models.ForeignKey(Coaches, on_delete=models.CASCADE)
I did what I always do in such situations where I encounter problems I have not seen before, I pulled his branch and started working on my own solution. I changed the table he was joining and added another foreign key to that table to ensure that I could get all the data I wanted. This small exercise made me realise just how important it is to design your database well.
def team_home(request):
jointables= Players.objects.select_related('TeamID', 'Coach')
playerQueryset = jointables.order_by('-TeamID', 'PlayerName')
context = {'team' : playerQueryset}
return render(request, 'SoccerApp/SoccerApp_page.html', context)
Printing to the console showed me I was getting all the data I wanted to, and then it was just a matter of passing it to the template. This was fun. I really should play with the database more often!
Comments
Post a Comment