django tables2加入

时间:2013-03-27 16:39:55

标签: django django-tables2

我希望使用django中的tables2进行多次连接

 --- 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>

结果:

在架构专栏中,它显示了......“架构对象”,对于应该有architecture_name的每个实例

如何让“JOINS”工作? 谢谢。

1 个答案:

答案 0 :(得分:2)

为了让Architecture模型返回架构名称,请添加类似

的内容
def __unicode__(self): 
    return self.architecture_name 
建筑类下的

。我认为这应该有效。此外,如果您想返回多列

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

请记住,您可以返回任何格式化的字符串