繁体   English   中英

使用django_tables2显示不同的模型

[英]Displaying different models with django_tables2

我对django很陌生,因此,如果这是一个新手问题,对不起。 我想知道是否可以使用django_tables2显示来自不同模型的列? 我想显示一个表格,其中包含Order_product模型中的所有列,但是我还想包括Orders模型中的customer和publication_date列吗? 我已经阅读了django_tables2文档,但是并没有什么帮助。

#models.py
class Customer(models.Model):
    costumer_id=models.IntegerField(max_length=5)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)


    def __unicode__(self):
        return self.first_name

class Product(models.Model):
    product_id=models.IntegerField(max_length=5)
    product_name=models.CharField(max_length=60)
    product_price=models.DecimalField(max_digits=5, decimal_places=2)


    def __unicode__(self):
            return self.product_name


class Orders(models.Model):
    order_id = models.CharField(max_length=5)
    customer = models.ForeignKey(Customer)
    publication_date = models.DateField()

    def __unicode__(self):
        return self.order_id


class Order_product(models.Model):
    order_id2 = models.ForeignKey(Orders)
    product_id2 = models.ForeignKey(Product)

不确定我是否理解您的问题,为什么不使用多对多关系? 请参阅此处的文档: https : //docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

class Orders(models.Model):
    order_id = models.CharField(max_length=5)
    customer = models.ForeignKey(Customer)
    publication_date = models.DateField()
    products = models.ManyToMany(Product)

    def __unicode__(self):
        return self.order_id

您可以从订单中访问产品:

>>> order = Orders.objects.all()[0]
>>> for product in order.products:
       print product.prodcut_name
       ...

假设您要基于Order_product查询集创建表。

class Order_productTable(tables.Table):
    order_id2 = tables.Column()
    product_id2 = tables.Column()
    customer = tables.Column(accessor="order_id2.customer")
    publication_date = tables.Column(accessor="order_id2.publication_date")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM