【发布时间】: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