1
遞歸多對多關係的「到」模型假設下面的模型:訂貨上的場中在Django
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',)
我怎樣才能獲取與給定類別相關的Category對象,同時保持排序?使用.distinct()
即使下面的代碼將產生正確的類別對象,而不是在正確的順序,以及包括在查詢中設置重複的條目:
relations = CategoryRelation.objects.filter(source = self)
Category.objects.filter(relation_target__in = relations).order_by('related')