Filipe
Filipe

Reputation: 331

Store a matrix in Django

I have the following matrix:

        item_1  item_2  item_3
item_1       1       0       0
item_2       0       2       0
item_3       0       0       3

What is the best way to store this matrix into django, so that in the future I can retrieve an entire column (being able to see the ID of each row), and use it to perform some calculations in a view?

Obs: This matrix is going to have thousands of columns and rows.

Upvotes: 0

Views: 623

Answers (1)

Blackeagle52
Blackeagle52

Reputation: 1986

Probably best to make an Cell model, with 3 fields; column, row, value.

class Cell(models.Model):
    col = models.CharField(max_length=50, index=True)
    row = models.CharField(max_length=50, index=True)
    value = models.IntegerField()
    
    class Meta:
        unique_together = ('col', 'row')

With this, you can do easy calculations.

col_sum = Cell.objects.filter(col='Abc').aggregate(sum=Sum('value'))['sum']
row_sum = Cell.objects.filter(row='Zyx').aggregate(sum=Sum('value'))['sum']

Upvotes: 1

Related Questions