<p><strong>更新</p>
<p>这是一个新的解决方案,它考虑到了这样一个事实:您实际上并没有实例化类,而是直接使用类对象。你知道吗</p>
<p>因为<code>Device79</code>必须在<code>Device79table.Meta</code>之前定义,所以不能告诉<code>Device79</code>在它自己的定义中使用哪个表。你甚至不能在<code>Device79table</code>期间这样做,因为它还不存在。你知道吗</p>
<p>因此,您需要在定义相应的表之后告诉<code>Device79</code>使用哪个表。你知道吗</p>
<p>如您所见,我也选择不使用动态变量名,而是在其他变量中使用一个明确定义的对象。动态变量名使代码更难阅读和维护。你知道吗</p>
<p><strong>型号.py</strong></p>
<pre><code>class Device79(models.Model):
table = None # Optional, but cleaner.
</code></pre>
<p><strong>表格.py</strong></p>
<pre><code>import models
class Device79table(tables.Table):
class Meta:
# link to datasource
model = models.Device79
attrs = {"class": "paleblue"}
# once the table is defined, we can tell Device79 which table to use.
models.Device79.table = Device79table
</code></pre>
<p><strong>视图.py</strong></p>
<pre><code>import tables # "from tables import Device79table" would work too.
from models import Device79
# You need to import tables, even if you access the tables from the models,
# because this is where we tell the device which table to use.
def function(device)
table = device.table(device.objects.all())
table.draw()
function(Device79)
</code></pre>
<p>通常,循环导入不是问题,只要您导入模块而不是单个对象,但是由于您需要在定义表的过程中直接访问模型,因此无法在<code>models.py</code>中导入表。这就是为什么我们改变<code>tables.py</code>中的设备来告诉它使用哪个表,而不是直接在<code>models.py</code>中设置它。你知道吗</p>
<p>这样,我们保持导入链如下:<code>views -> tables -> models</code>和<code>models</code>从不尝试导入<code>tables</code>,但这也意味着我们必须至少在某处导入<code>tables</code>一次才能完成模型定义。你知道吗</p>
<p>这有点令人惊讶,但我想不出一个更干净更简单的方法来做这件事,而只处理类对象,而不是实例。你知道吗</p>