次のモデルを想定しています。
class Category(models.Model):
related = models.ManyToManyField('self', symmetrical = False, through = 'CategoryRelation', null = True, blank = True)
次の中間の「から」の関係を想定します。
class CategoryRelation(models.Model):
source = models.ForeignKey('Category', null = False, blank = False, verbose_name = _('source'), related_name = 'relation_source')
target = models.ForeignKey('Category', null = False, blank = False, verbose_name = _('target'), related_name = 'relation_target')
order = models.PositiveIntegerField(_('order'), null = False, blank = True, default = 0)
class Meta:
ordering = ( 'order', )
順序を維持しながら、特定のカテゴリに関連するカテゴリオブジェクトを取得するにはどうすればよいですか?次のコードは、正しい順序ではなく正しいカテゴリオブジェクトを生成し、次を使用している場合でもクエリセットに重複するエントリを含めます.distinct()
。
relations = CategoryRelation.objects.filter(source = self)
Category.objects.filter(relation_target__in = relations).order_by('related')