Ordering a django model on many-to-may field. Denormalization required?
I have a system for composing items from parts in certain categories
For instance take the following categories:
- 1: (Location)
- 2: (Material)
And the following parts:
- Wall (FK=1)
- Roof (FK=1)
- Roof (FK=1)
- Brick (FK=2)
- Tile (FK=2)
- Wood (FK=2)
To compose these items: Wall.Brick, Roof.Wood, Wall.Wood
class Category(models.Model):
ordering = models.IntegerField()
desc = models.CharField()
class Part:
name = models.CharField()
category = models.ForeignKey(Category)
class Meta:
unique_together = ('name', 'category')
ordering = ['category','name']
class Item:
parts = ManyToManyField(Part)
def __unicode__(self):
return ".".join([p.name for p in self.parts.all()])
Now the question: how do i ord开发者_开发技巧er the Items? I'd prefer to have them ordered ascending by the composed name, but dont know how.
One way of doing things could be an extra field for the name, that gets updated on the save() method. That would mean denormalizing the model...
If I understand correctly, sort key do not exist in database, so database cannot sort it (or at least on trivially, like using Django ORM).
Under those conditions, yes - denormalize.
It's no shame. As said, normalized dataset is for sissies...
精彩评论