我是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)
答案 0 :(得分: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
...
答案 1 :(得分: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")