Question

I am quite new to django, I am therefore sorry if this is a newbie question. I want to know if there is a way to display columns from different models with django_tables2? I want to display a table with all the columns from the Order_product models, but I also want to include the customer and publication_date columns from the Orders model? I have read the django_tables2 documentation, but it wasn't much of a help.

#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)
Was it helpful?

Solution

This is assuming you want to create a table based on a Order_product queryset.

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")

OTHER TIPS

Not sure I understand your questions, why not use many to many relationship? See the documentation here: 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

And you can access the products from the order:

>>> order = Orders.objects.all()[0]
>>> for product in order.products:
       print product.prodcut_name
       ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top