[英]In Django Tables2, how do you make a column show text from a table referenced by a foreign key?
在阅读了我能找到的所有文档和答案,并烧了一整天之后,我仍然无法完成这项工作。 使用 Django Tables2,我想显示仪器列表; Instruments 表包含 InstrumentType 表的外键。 当我列出仪器及其属性时,我想使用外键替换另一个表中的文本仪器类型描述。 我已经尝试了双下划线和其他访问器技术的所有组合,但到目前为止,我得到的只是可怕的——在专栏中。 (仅显示记录 ID 有效)。
from .models import Instrument
from django_tables2 import A
from instrumenttypes.models import InstrumentType
class InstrumentTable(tables.Table):
id = tables.LinkColumn('instrument_details', args=[A('station_id')])
class Meta:
model = Instrument
template_name = "django_tables2/bootstrap.html"
fields = ("id", "instrument", "nickname", "serialNo",
"instrument__instrumenttype_id__instrumenttypes__id_instrumentType" )
涉及的模型有: Instruments model.py
from django.db import models
from instrumenttypes.models import InstrumentType
from stations.models import Station
# Create your models here.
class Instrument(models.Model):
instrument = models.CharField(max_length=40)
instrumenttype = models.ForeignKey(InstrumentType, on_delete=models.CASCADE, null=True)
station = models.ForeignKey(Station, on_delete=models.CASCADE, default=1)
serialNo = models.CharField(max_length=60, null=True, blank=True)
dateAdded = models.DateTimeField("Date Added", null=True, blank=True)
dateRemoved = models.DateTimeField("Date Removed", null=True, blank=True)
status = models.CharField(max_length=10, null=True, blank=True)
nickname = models.CharField(max_length=40, null=True, blank=True)
InstrumentTypes 模型.py
from django.db import models
class InstrumentType(models.Model):
instrumentType = models.CharField(max_length=40)
结果输出:
ID Instrument Nickname SerialNo Instrumenttype
4 instr2 nock2 123 —
我也一直在努力让某些东西起作用(但我终于做到了),而且我发现这些例子太简短了。
我认为您想在 Meta 类中摆脱这些东西
"instrument__instrumenttype_id__instrumenttypes__id_instrumentType"
我认为Meta.fields
应该只是一个字段名称列表,并且您从稍后将传递给 IntrumentTable 构造函数的对象类型的角度来引用另一个表中的属性(并且在Meta.model
属性:
from django_tables2.utils import Accessor
class InstrumentTable(tables.Table):
instrument_type = tables.Column(accessor=Accessor('instrumenttype.name'))
class Meta:
model = Instrument
template_name = "django_tables2/bootstrap.html"
fields = ("id", "instrument", "nickname", "serialNo", "insrument_type")
然后,在视图中,创建一个 InstrumentTable 的实例
def myview(request):
table_to_render = InstrumentTable(Instrument.objects)
return render(request, sometemplate, {table: table_to_render})
你没有展示你的观点,我知道可能有不同的方式。 如果您在某个地方的仓库中有全部内容,请留下链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.