0

我希望在 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>

结果:

在“架构”列中,它显示....“架构对象”对于每个应该有架构名称的实例

我怎样才能让“JOINS”工作?谢谢。

4

1 回答 1

2

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

def __unicode__(self): 
    return self.architecture_name 

在建筑类下。我认为这应该有效。另外,如果您想返回多列

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

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

于 2013-03-27T19:47:51.793 回答