如何在django中获取每个对象(干预)多对多关系的对象(设备)列表

How to get list of object(equipement) for each object (intervention) manytomany relationship in django

型号设备:

    class Equipement(models.Model):
        nom_equipement=models.CharField(max_length=60)
        qte_stock=models.IntegerField()
        panne=models.ManyToManyField(Panne)

模型干预:

    class Intervention(models.Model):
        Titre_intervention = models.TextField(max_length=255)
        date_intervention = models.DateField(auto_now_add=True)
        type_panne = models.ForeignKey(Panne,on_delete=models.CASCADE)
        etat = models.CharField(max_length=30)
        description = models.TextField(max_length=255)
        image = models.ImageField(blank=True,null=True,upload_to='medial/%Y/%m/%D')
        equipements = models.ManyToManyField(Equipement)
        clients = models.ForeignKey(Client,on_delete=models.CASCADE,default=True)

模型干预与多对多关系:

所以当我添加新的 "intervention" 时,它会添加到 table 关联

我需要列出每次干预的所有设备这是我的观点:

    def mes_intervention(request):
            if 'id_client' in request.session:
                get_idClient=request.session['id_client']
                Interv_client = Intervention.objects.all().filter(clients=get_idClient)

                context = {
                    'intervention':Interv_client
                    }

                return render(request, 'clients/mes-intervention.html',context)

这是我列出所有对模板的干预的地方html

附带说明一下,您有点混淆了复数和单数。一个外键指向一个模型:

  • client = models.ForeignKey(Client,on_delete=models.CASCADE,default=True) # singular

一个查询集returns多个对象:

  • context = { 'interventions': Interv_client}

虽然您不能使用参数调用模板中的函数,但您可以调用不带参数的对象方法。所以,你实际上可以这样做:

{% for item in interventions %}
   ...
   {% for equipment in item.equipements.all %}
       {{ equipment.qte_stock }}
   {% endfor %}
{% endfor %}