![](/img/trans.png)
[英]Django ORM Accessing related many-to-many objects through queryset
[英]Accessing many-to-many details with through model in Django template
我有一個這樣的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 %}
您可以,但您需要正確訪問它,您可以使用work.instrumentation_set
訪問Instrumentation
:
{% 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'
,這可能並不理想。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.