Question

I wish to do several joins using tables2 in django

 --- models.py (abbrev.)

from django.db import models
import django_tables2 as tables2

class Architecture (models.Model):
    architecture_id = models.AutoField(primary_key=True)
    architecture_name = models.CharField("Architecture",max_length=20)
    architecture_comment =models.CharField("Comments",null=True,blank=True,max_length=200)

class Server (models.Model):
    server_id  = models.AutoField(primary_key=True)
    server_name = models.CharField("Server Name",max_length=200,unique=True)
    server_ip = models.IPAddressField("Server IP")
    server_serial = models.CharField("Serial No.",max_length=25,null=True,blank=True)
    server_mem = models.PositiveIntegerField("Mem (MB)",null=True,blank=True)
    server_architecture = models.ForeignKey(Architecture)

class ServersTable(tables2.Table):
    architecture = tables2.Column(accessor='architecture.architecture_name')


--- views.py

from django.http import HttpResponse
from servers.models import Server
from django.shortcuts import render

def index(request):
    return render(request, "index.html", {"server": Server.objects.all()})

--- index.html 
{% load render_table from django_tables2 %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />

<link rel="stylesheet"     href="http://myhost/django_tables2/themes/paleblue/css/screen.css" />
<title>myhost</title>
</head>
<body>
 {% render_table server %}
</body>

Results:

in the Architecture column it shows .... "Architecture object" for each instance where there should be an architecture_name

How can I get the "JOINS" to work ? Thanks.

Was it helpful?

Solution

For getting Architecture model to return architecture name add something like

def __unicode__(self): 
    return self.architecture_name 

under Architecture class. I think that should work. Also if you want to return multiple columns

def __unicode__(self): 
    return "%s, %s" % (self.architecture_name, self.architecture_comment)

Remember that you can return any formatted string

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top