Thursday, June 17, 2010

Django: How can I add weight/ordering to a many to many relationship?

Programmer Question

I'm having Pages with TextBlocks on them. Text Blocks may appear on different pages, pages may have several text blocks on them. Every page may have these blocks in an ordering of it's own.
This can be solved by using a separate through parameter. Like so:



class TextBlock(models.Model):
title = models.CharField(max_length=255)
text = models.TextField()

class Page(models.Model):
textblocks = models.ManyToManyField(TextBlock, through=OrderedTextBlock)

class OrderedTextBlock(models.Model):
text_block = models.ForeignKey(TextBlock)
product_page = models.ForeignKey(ProductPage)
weight = models.IntegerField()

class Meta:
ordering = ('weight',)


But I'm not very enthousiastic about the violations of DRY for my app. (There's a lot of ordered ManyToMany relations). Is there a recommended way to go about this?



Find the answer here

1 comment:

  1. I think if you take out the "through" table, the textblocks for each page will be ordered in whatever order the textblocks would be ordered in normally, so you could add your weight field to the TextBlock model. The only time this wouldn't work is if you wanted TextBlock "1" to come before TextBlock "2" on one page, but you wanted the opposite on another page (though you could do some custom sorting for each page within your view).

    ReplyDelete

LinkWithin

Related Posts with Thumbnails