【问题标题】:Accessing many-to-many details with through model in Django template在 Django 模板中通过模型访问多对多细节
【发布时间】:2020-05-26 16:09:29
【问题描述】:

我有一个这样的models.py:

class Work(models.Model):
[...]
    instrumentations = models.ManyToManyField('Instrument', 'Percussion',
        through='Instrumentation',
        blank=True)

class Instrument(models.Model):
    name = models.CharField(max_length=100)
    family = models.CharField(max_length=20, default='')

class Percussion(models.Model):
    name = models.CharField(max_length=100)

class Instrumentation(models.Model):

    players = models.IntegerField()
    work = models.ForeignKey(Work, on_delete=models.CASCADE)
    instrument = models.ForeignKey(Instrument, on_delete=models.CASCADE)
    percussion = models.ManyToManyField(Percussion, blank=True, default=None) # Ideally percussions should be in the Instrument model with family 'percussion', though I don't know how to make Django like that. A separate model is a good workaround for me.

我的看法:

def work_edit_view(request, id=id):

    InstrumentFormSet = inlineformset_factory(Work, Work.instrumentations.through, extra=1, can_delete=True,
    fields=('instrument', 'percussion', 'players', 'work'), widgets={
    'work': forms.HiddenInput(),
    'players': forms.NumberInput(attrs={'placeholder': 'Number of players'})
    form_details = InstrumentFormSet(request.POST or None, instance=obj_work, initial=[{'work' : obj_work.id}], prefix='instruments')

})

数据已正确保存在我的输入表单中,所以这不是问题。我的问题是可视化模板中的信息。我只能访问“乐器”,不能访问“打击乐器”或“演奏者”。我做错了什么?

    {% for instrument in work.instrumentations.all %}
    {{ instrument }} {{ instrument.players }} # only instrument is output.

      {% for percussion in instrument.percussion.all %} # this looks to be empty.
      Percussion {{ forloop.counter }} ({{ percussion.players }}) # No luck here :(
      {% endfor %}

【问题讨论】:

  • 一个ManyToMany 字段不能访问多个模型。它使用Percussion 作为related_name

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


【解决方案1】:

可以,但需要正确访问,可以通过work.instrumentation_set访问Instrumentations:

{% for instrumentation in work.instrumentation_set.all %}
    {{ instrumentation.instrument }} {{ instrumentation.players }}

    {% for percussion in instrumentation.percussion.all %}
        Percussion {{ forloop.counter }} ({{ percussion.players }})
    {% endfor %}
{% endfor %}

注意ManyToManyField 不能引用多个模型。第二个参数是related_name,所以你把关系的名字反过来设置为'Percussion',这可能不太理想。

【讨论】:

  • 非常感谢,instrumentation_set 是关键。感谢您发现 ManyToManyField 中的第二个参数,这是我出于绝望添加的内容。
猜你喜欢
  • 2018-12-05
  • 1970-01-01
  • 2012-12-31
  • 2011-03-23
  • 2012-11-30
  • 1970-01-01
  • 2014-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多