如何从不同的相关模型访问多对多关系?

时间:2020-02-04 15:49:55

标签: django django-models django-templates django-views django-queryset

我有以下型号:

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)
  1. 如何从工作中访问仪器对象下的所有仪器?

例如:

piece = Work_Music.objects.get(pk=self.kwargs['pk'])

我尝试了piece.instrumentation_set.all。那没用吗?

  1. 您如何从仪器获得访问权限?

instrumentation = Instrumentation.objects.get(instrumentation__work=self.kwargs['pk'])

我猜想您可以抓住对象时进行for循环。

  1. 您如何从Instrumentmap获取访问权限?

InstrumentMap = InstrumentMap.objects.filter(instrumentation__work=self.kwargs['pk']).order_by('order')

1 个答案:

答案 0 :(得分:2)

  1. 乐器是外键,因此必须使用:

    piece = Work_Music.objects.get(pk=self.kwargs['pk'])
    piece.instrumentation.instrumentmap.all() 
    
  2. 您可以使用反向many_to_one关系:

    instrumentation = Instrumentation.objects.get(work__id=self.kwargs['pk'])
    
  3. 您可以使用:

    instrument_maps = InstrumentMap.objects.filter(instrumentation__work__id=self.kwargs['pk'])