我想要实现的是将我的django模型中的一个加载到表中,并添加一些列,其中附加列是基于行中2个单元格的查询。 例如,如果Person模型具有名字和姓氏,则附加列将是“从another_table中选择top 1,其中fname = fname和lname = lname”
我尝试使用django-tables2,这是我的代码:
#models.py:
from django.db import models
class Person(models.Model):
fname = models.CharField(max_length=10)
lname = models.CharField(max_length=10)
age = models.IntegerField()
def __unicode__(self):
return '%s %s : %i' % (self.fname, self.lname, self.age)
class Map(models.Model):
person = models.ForeignKey(Person)
info = models.CharField(max_length=10)
def __unicode__(self):
return str(self.person)
# views.py
from django.shortcuts import render
from .models import Person
from django_tables2 import RequestConfig
from .models import Person
from .tables import PersonTable
def people(request):
table = PersonTable(Person.objects.all())
RequestConfig(request).configure(table)
return render(request, 'people.html', {'people': table})
#tables.py:
import django_tables2 as tables
from .models import Person
class PersonInfo(tables.Column):
def render(self, value):
return str(value) # <<====== this is later going to be my query
class PersonTable(tables.Table):
info = PersonInfo()
selection = tables.CheckBoxColumn(accessor="pk", orderable=False)
class Meta:
model = Person
有3个问题,感谢任何帮助:
我已经从列中对PersonInfo进行了细分,但信息值为空。
当制作这个没有自定义表格的示例应用程序时,表格看起来不错,但现在它没有显示表格边框/格式,浏览器也表明screen.css已成功加载所以我不知道为什么它看起来像这样。
答案 0 :(得分:1)
以下是我理解你的问题的方法,我就是这样做的:
# models.py
class Person(models.Model):
name = models.CharField(max_length=100)
age = models.IntergerField()
class Info(models.Model):
the_person = models.ForeignKey(Person)
info = models.CharField(max_length=200)
# views.py
# I'm using Class Based Views from Generic Views
class PersonDetail(ListView):
# automatically uses pk of
# model specified below as slug
model = Person
现在在你的模板中,你可以有这样的东西:
# html. Just a rough html below. I hope it gives you the idea. Might not tabulate the data properly, but the point is is to have both model data in templates, then simply use {% for %} loop to list one data in one column or more columns of the table and then whatever model(s) in the other columns.
<table style="width:100%">
<tr>
<td>Name</td>
<td>Age</td>
<td>Info</td>
</tr>
{% for object in object_list %}
<tr>
<td>{{ object.name }}</td>
<td>{{ object.age }}</td>
{% for i in object.the_person.set_all %}
<td>{{ i.info }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
如果您希望相互检索两个模型“Non-ForeignKey-ed”,则可以使用上下文对象。 See here