2013-10-16 23 views
2

我對django相當陌生,因此如果這是一個新手問題,我很抱歉。我想知道是否有方法使用django_tables2顯示來自不同模型的列?我想顯示一個包含Order_product模型中所有列的表,但是我還想包含訂單模型中的customer和publication_date列?我已經閱讀了django_tables2文檔,但沒有太多幫助。用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) 

回答

0

這是假設你想創建一個基於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") 
0

不知道我理解你的問題,爲什麼不使用多對多的關係? 在這裏看到的文檔: 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 
     ...