Django

时间:2016-09-01 12:41:40

标签: python mysql django

我坚持(我认为)Django上的一个虚假错误,我无法找到它的错误。

On" catalog / models.py"我有(它连接到MySQL数据库):

from django.db import models

class Application(models.Model):
    nameApp = models.CharField(max_length=50)
    tarification = models.ForeignKey(Tarification)

然后,我使用 django-tables2 Doc to fill tables)在Django上制作表格,所以在我的 tables.py 上我有:

import django_tables2 as tables
from catalog.models import AppCost, Application, Tarification


class BillTable(tables.Table):
    class Meta:
        appName = Application.nameApp
        userApp = AppCost.userApp
        tarifName = Tarification.nameTarif
        tarifCost = Tarification.cost
        startTime = AppCost.startTime
        finishTime = AppCost.finishTime
        totalCost = AppCost.totalCost
        # add class="paleblue" to <table> tag
        attrs = {'class': 'paleblue'}

我在渲染网站时遇到错误:

type object 'Application' has no attribute 'nameApp'

来自 BillTable

appName = Application.nameApp

但是,看看&#34;数据库&#34; Pycharm上的窗口我看到了表架构,它是:

  • catalog_application
    • ID
    • tarification_id
    • nameApp
    • 其他东西

使用MySQL Workbench查看架构看起来是一样的。那么,为什么我会收到此错误?

问候。

2 个答案:

答案 0 :(得分:1)

您对如何使用django-tables非常困惑。您需要在Meta类中指定一个模型,然后只需要fields属性来添加该模型中的字段列表(作为字符串)以进行显示。您不能只指定三个任意模型中的字段。

答案 1 :(得分:1)

正如丹尼尔罗斯曼上面提到的,你可能会寻找的代码如下,它不需要新的模型:

import django_tables2 as tables
from catalog.models import AppCost, Application, Tarification

class AppCostTable(tables.Table):
    userApp = tables.Column()
    startTime = tables.Column()
    finishTime = tables.Column()
    totalCost = tables.Column()

    class Meta:
        model = AppCost

class ApplicationTable(tables.Table):
    appName = tables.Column(accessor='nameApp')
    class Meta:
        model = Application

class TarificationTable(tables.Table):
    tarifName = tables.Column(accessor='nameTarif')
    tarifCost = tables.Column(accessor='cost')
    class Meta:
        model = Tarification


class BillTable(AppCostTable, ApplicationTable, TarificationTable, tables.Table):
    pass

如果您不介意拥有其他模型,那么您可以在 catalog.models 中添加新的Bill模型:

class Bill(models.Model):
    application = models.ForeignKey('Application')
    appcost = models.ForeignKey('AppCost')
    tarification = models.ForeignKey('Tarification')

在您的表格文件中:

from catalog.models import Bill

class BillTable(tables.Table):
    appName = tables.Column(accessor='application.nameApp')
    tarifName = tables.Column(accessor='tarification.nameTarif')
    tarifCost = tables.Column(accessor='tarification.cost')
    userApp = tables.Column(accessor='appcost.userApp')
    startTime = tables.Column(accessor='appcost.startTime')
    finishTime = tables.Column(accessor='appcost.finishTime')
    totalCost = tables.Column(accessor='appcost.totalCost')


    class Meta:
        model = Bill