社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

Django如何在模板中设置model1.model2.all()?

Julien Mertz • 4 年前 • 776 次点击  

我正在构建一个网站,我有两个模型,我们称之为Model1和Model2,Model2有一个指向Model1的foreignKey属性。我有一个模板,在这个模板中,我可以访问数据库Model1表中所有条目的列表。我要做的是对所有与特定条目model1相关联的条目model2执行for循环。 在某种意义上,我可以做到: for model2 in model1.model2_set.all(): 但我怎样才能在模板中做到这一点呢? 我试过了 {% for model2 in model1.model2_set.all %} 但那不管用。

提前谢谢!

编辑: 模型.py

class Plat(models.Model):
    titre = models.CharField(max_length = 100)
    description = models.TextField(null = True)
    allergenes = models.TextField(null = True)
    prix = models.IntegerField(verbose_name = "Prix par portion")
    chef = models.ForeignKey('inscription.Chef', on_delete = models.CASCADE)
    date_prep = models.DateTimeField(default=timezone.now, verbose_name="Date et heure de préparation")
    nb_portions = models.IntegerField(verbose_name = "Nombre de portions disponibles")
    photo = models.ImageField(upload_to = "photos_plat/")
    is_ordered = models.BooleanField(default=False)

    class Meta:
        verbose_name = "Plat"
        ordering = ['date_prep']

    def __str__(self):
        return self.titre


class Commande(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE)
    plat = models.ForeignKey('Plat', on_delete = models.CASCADE) # models.PROTECT pour pas supprimer, models.CASCADE pour supprimer.
    nb_portions = models.IntegerField(verbose_name = "Nombre de portions")
    date = models.DateTimeField(verbose_name="Date de commande")
    livraison = models.BooleanField(default=False)
    adresse_livraison = models.CharField(max_length = 100, verbose_name = "Adresse de livraison", blank = True)

    class Meta:
        verbose_name = "Commande"
        ordering = ['date']

模型1是Plat,模型2是command

视图.py

def mes_plats(request):
    return render(request, 'actualites/mes_plats.html', {'my_meals': Plat.objects.filter(chef=request.user.useradvanced.chef, date_prep__gte = date.today())})

mes_plats.html

{% for plat in my_meals %}
   {% if plat.is_ordered %}
      <ul>
      {% for commande in plat.commande_set.all %}
          <li> {{ commande.user.useradvanced }} : {{ commande.nb_portions}} portions.</li>
      </ul>
   {% else %}
      Ce plat n'a pas encore été commandé par un utilisateur.
   {% endif %}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52194
 
776 次点击  
文章 [ 1 ]  |  最新文章 4 年前
arjun
Reply   •   1 楼
arjun    4 年前

首先你需要通过 model1 通过如下上下文实例到模板:

   def your_view(request,pk):
      model1_instance = YourModel.objects.get(pk=pk)
      return render(request,'your_template',{'model1':model1_instance})

现在在你的模板中 {% for model2 in model1.model2_set.all %} 应该有用。

编辑: 如果已将queryset传递给模板,则可以这样做

{% for obj1 in your_model1_queryset %}
   {% for obj2 in obj1.model2_set.all %}
      ...
   {% endfor %}
 {% endfor %}