How to have a different models.ForeignKey related_name for each linked objects of same model?

I’m working with Django Rest to have multiple “text block” objects linked with the document object. I’ve accomplished this with a simple models.ForeignKey feature so far.

However, I’m rendering all of these text blocks in multiple columns in the front end. The Textblock model will have a column field to determine which goes to which column. Since the order of these text blocks matter, I was afraid of having them all mixed together under single "all_columns" field So far, I figured the easiest way is to let DRF return something like the following:

{
    "name": "Comparing Two Characters",
    "column_A": [
        {
            "title": "Text Block",
            "body": "lorem ipsum blah blah"
            "col": 1
        }
    ],
    "column_B": [
        {
            "title": "Text Block 2",
            "body": "lorem ipsum blah blah"
            "col": 2
        },
            {
            "title": "Text Block 3",
            "body": "lorem ipsum blah blah"
            "col": 2
        }
    ]
}

How would I be able to implement something like this? I’m not sure if using related fields is even ideal for such cases. I would appreciate any help!

Here’s my current models.py code for reference:

class Document(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    # other fields
    def __str__(self):
            return self.name

class TextBlock(models.Model):
    id = models.AutoField(primary_key=True)
    document = models.ForeignKey(Document, related_name='blocks', on_delete=models.CASCADE)
    col = models.CharField(max_length=100)
    title = models.CharField(max_length=100)
    body = models.CharField(max_length=100)

Try this:

from collections import defaultdict

class Document(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    # other fields
    def __str__(self):
            return self.name

    def blocks_by_column(self):
        block_group = defaultdict(list)
        for block in self.blocks.all():
            block_group[block.col].append(block)
        return block_group


class TextBlock(models.Model):
    id = models.AutoField(primary_key=True)
    document = models.ForeignKey(Document, related_name='blocks', on_delete=models.CASCADE)
    col = models.IntegerField()
    title = models.CharField(max_length=100)
    body = models.CharField(max_length=100)

If you have a ordering mechanism i.e. an order column, you can change self.blocks.all() to self.blocks.order_by(<column>).all(). You can later change the keys of blocks_group as you see fit. 1 -> column_A.

Back to Top