Accessing many-to-many details with through model in Django template

HBMCS

I have a models.py like this:

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.

My view:

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')

})

The data gets saved correctly in my input form, so that's not an issue. My problem is visualising the information in my template. I can only access the 'instrument', not my 'percussion' or my 'players'. What am I doing wrong?

    {% 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 %}
Willem Van Onsem

You can, but you need to access it correctly, you can access the Instrumentations with work.instrumentation_set:

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

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

Note: that a ManyToManyField can not refer to multiple models. The second parameter is the related_name, so you set the name of the relation in reverse to 'Percussion', which might not be ideal.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Accessing has_many objects from model in rails

분류에서Dev

Django query filter many to many to many etc

분류에서Dev

Django contains on a many to many field

분류에서Dev

Many-to-Many relationship in Django

분류에서Dev

ManyToManyField "through"관계없이 Django Filtering Many-to-Many 관계

분류에서Dev

Quickly browse through many PDFs

분류에서Dev

Self referencing one to many Model

분류에서Dev

How to add many-to-many relationships through a form?

분류에서Dev

has_many 후 has_many : through?

분류에서Dev

Eloquent ORM - retrieve models not related to the given model (Many to Many relationship)

분류에서Dev

link to relationship name in has_many :through

분류에서Dev

has_many : through 양식

분류에서Dev

Rails has_many : through with the where 절

분류에서Dev

Finding Users with has_many :through

분류에서Dev

Make has_many :through not deleteable

분류에서Dev

Join has_many :through attributes

분류에서Dev

Has Many Through. How to get the access?

분류에서Dev

Rails 4: has many through association error

분류에서Dev

has_many / : through rails4

분류에서Dev

Rails has_many : through, undefined method

분류에서Dev

Has-Many-Through 관계

분류에서Dev

Django template not iterating through list

분류에서Dev

Adding a one-to-many property to the Identity Model

분류에서Dev

Accessing Choices Value of PositiveSmallIntegerField in Django Template

분류에서Dev

has_one : through 및 has_many : through

분류에서Dev

Has_Many_Through가 Many를 통과로 푸시하지 못함

분류에서Dev

has_many : through와 has_and_belongs_to_many 중 선택- "should"또는 "must"

분류에서Dev

ActiveAdmin 필터 : has_many : through 속성

분류에서Dev

Can a has_many :through association have other associations?

Related 관련 기사

뜨겁다태그

보관