我有以下型号:
class Instrument(MPTTModel):
name = models.CharField(max_length=100, null=True, blank=True)
class Instrumentation(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)
category = models.CharField(max_length=100, null=True, blank=True)
instrument = models.ManyToManyField('Instrument', through='InstrumentMap')
class InstrumentMap(models.Model):
instrumentation = models.ForeignKey(Instrumentation, verbose_name=_('instrumentation'), related_name='instrumentmap', null=True, blank=True, on_delete=models.PROTECT)
instrument = models.ForeignKey(Instrument, verbose_name=_('instrument'), related_name='instrumentmap', null=True, blank=True, on_delete=models.PROTECT)
numbers = models.IntegerField(null=True, blank=True)
class Work_Music(MPTTModel, Work):
instrumentation = models.ForeignKey(Instrumentation, verbose_name=_('instrumentation'), related_name='work', null=True, blank=True, on_delete=models.PROTECT)
例如:
piece = Work_Music.objects.get(pk=self.kwargs['pk'])
我尝试了piece.instrumentation_set.all
。那没用吗?
instrumentation = Instrumentation.objects.get(instrumentation__work=self.kwargs['pk'])
我猜想您可以抓住对象时进行for
循环。
InstrumentMap = InstrumentMap.objects.filter(instrumentation__work=self.kwargs['pk']).order_by('order')
答案 0 :(得分:2)
乐器是外键,因此必须使用:
piece = Work_Music.objects.get(pk=self.kwargs['pk'])
piece.instrumentation.instrumentmap.all()
您可以使用反向many_to_one关系:
instrumentation = Instrumentation.objects.get(work__id=self.kwargs['pk'])
您可以使用:
instrument_maps = InstrumentMap.objects.filter(instrumentation__work__id=self.kwargs['pk'])