在 Django Tables2 中,如何使列显示外键引用的表中的文本?

问题描述 投票:0回答:1

在阅读了我能找到的所有文档和答案并花费了一整天时间后,我仍然无法完成这项工作。使用 Django Tables2,我想显示仪器列表; Instruments 表包含instrumentsType 表的外键。当我列出仪器及其属性时,我想使用外键来替换其他表中的文本仪器类型描述。我已经尝试了双下划线和其他访问器技术的每种组合,但到目前为止我得到的只是列中可怕的 -- 。 (仅显示记录 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" )

涉及的型号有: 仪器型号.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)

仪器类型 model.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           —

我找到的最相关的在线参考是这里这里;但尝试过这些建议后,没有运气。我错过了什么?

python django foreign-keys
1个回答
1
投票

我也一直在努力让一些东西发挥作用(但我终于做到了),而且我发现这些示例太简短了。

我认为你想摆脱 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", "instrument_type")

然后,在视图中,创建一个InstrumentTable的实例

def myview(request):
    table_to_render = InstrumentTable(Instrument.objects)
    return render(request, sometemplate, {table: table_to_render})

你没有表达你的观点,我知道可能有不同的方式。如果您在某个存储库中拥有全部内容,请留下链接。

© www.soinside.com 2019 - 2024. All rights reserved.