我是一名学生,也是Django的新手,我们有一个项目,我们正在try 使用Django构建.在我构建这个项目的过程中,我偶然发现了一个问题,并且陷入了数周的困境.

我想在分页时在一个页面上显示与其父字段相关联的所有内联字段.当我试图用另外两个有外键的模型对模型进行分页时,我在模板中得到了一个奇怪的结果.我似乎不知道该怎么修.我在互联网上try 了几种方法,并阅读了许多论坛和讨论,但都没有用,到目前为止都没有奏效.以下是我的文件和一些图片:


(型号.py)

from django.db import models

class History(models.Model):
   BARANGAY = (
     ('Alegria','Alegria'),
     ('Bagacay','Bagacay'),
     ('Baluntay','Baluntay'),
     ('Datal Anggas','Datal Anggas'),
     ('Domolok','Domolok'),
     ('Kawas','Kawas'),
     ('Ladol','Ladol'),
     ('Maribulan','Maribulan'),
     ('Pag-Asa','Pag-Asa'),
     ('Paraiso','Paraiso'),
     ('Poblacion','Poblacion'),
     ('Spring','Spring'),
     ('Tokawal','Tokawal')
   )
  barangay_name = models.CharField(max_length=100,choices=BARANGAY,default='Alegria')
  barangay_img = models.ImageField(upload_to='history_imgs',blank=True)
  barangay_info = models.TextField()

class GeoHazard(models.Model):
  history = models.ForeignKey(History,related_name='geohazards',on_delete=models.CASCADE)
  geohazard_img = models.ImageField(upload_to='history_imgs',blank=True)
  date_published = models.CharField(max_length=100, null=True)
  geohazard_info = models.TextField()

class Assessment(models.Model):
   RATINGS = (
      ('HIGH','HIGH'),
      ('HIGH (Mitigated)','HIGH (Mitigated)'),
      ('MODERATE','MODERATE'),
      ('MODERATE (Mitigated)','MODERATE (Mitigated)'),
      ('LOW','LOW'),
      ('UNKNOWN','UNKNOWN'),
   )

   history = models.ForeignKey(History,related_name='assessment',on_delete=models.CASCADE)
   purok_name = models.CharField(max_length=50)
   purok_coordinates = models.CharField(max_length=100,default='unknown')
   flood_rating = models.CharField(max_length=100,choices=RATINGS,default='UNKNOWN')
   landslide_rating = models.CharField(max_length=100,choices=RATINGS,default='UNKNOWN')

在我的模型中.py我有父模型"历史"和另外两个模型"地质灾害"和"判断",都有外键.


admin-dashboard.png

(管理员py)

from django.contrib import admin

from auxiliary.models import (
   History, 
   GeoHazard,
   Assessment
)
class GeoHazardInline(admin.StackedInline):
   model = GeoHazard
   extra = 0

class AssessmentInline(admin.StackedInline):
   model = Assessment
   extra = 0

class HistoryAdmin(admin.ModelAdmin):
   inlines = [GeoHazardInline,AssessmentInline]

admin.site.register(History,HistoryAdmin)

在我的管理员.py我正在使用"StackedLine".我这样构造它,以便父模型"历史"可以有多个与之相关联的内联字段.


(views.py#1)

class history(ListView):
   model = History
   template_name = 'auxiliary/history.html'
   context_object_name = 'histories'
   paginate_by = 1

最初,我使用"ListView"利用其预构建的分页方法"paginate\u by",但通过这样做,模板导致了这一点(见下图).大家可以看到,内联字段也由"1"分页,其他内联字段与第一页分开.

template-views1.png)


(views.py#2)

class HistoryView(ListView):
   model = History
   template_name = 'auxiliary/history.html'
   context_object_name = 'histories'
   paginate_by = 1

def get_context_data(self, **kwargs):
       context = super(HistoryView, self).get_context_data(**kwargs)
       context.update({
           'geohazards': GeoHazard.objects.all(),
           'assessments': Assessment.objects.all()
          })

       return context

所以我try 了一种不同的方法;现在,通过使用get\u context\u数据覆盖"context",在我的"ListView"中传递3个模型.在这种方法中,所有内联字段都显示在我的模板template-views2-A.png中,但这一次它提出了一个新问题,即使所有内联字段都显示在模板中,但它没有与其关联的父字段一起显示.现在,当在我的分页按钮中 Select 一个新页面时,父字段改变了template-views2-B.png

此外,我还try 了"地质灾害".物体.过滤器(history_id=1)"在更新"context"字典时,但这不是解决方案,因为这只会从具有特定id的父字段中获取内联字段.然后我try 使用自定义模板标记django custom template-tags,但它不起作用.


(template.html)

{% for history in histories %}
                <div class="row m-0">
                  <div class="col-md-3 col-sm-12 mt-4">
                    <div class="card bg-transparent border-0">
                      <div class="car-body text-center">
                        <h3><u>{{ history.barangay_name}}</u></h3>
                        <img src="{{ history.barangay_img.url }}" width="180" height="180" class="rounded-circle">
                      </div>
                    </div>
                    
                  </div>
                  <div class="col-md-8 col-sm-12 mt-4" style="display: grid;place-items:center;">
                    <div class="card bg-transparent border-0">
                      <div class="car-body">
                        <p style="text-align:justify;">{{ history.barangay_info}}</p>
                      </div>
                    </div>
                  </div>
                </div>
                <hr>
              {% endfor %}

            {% if geohazards %}
                {% for hazard in geohazards %}
                  <div class="row m-0">
                    <div class="col-md-3 col-sm-12 mt-4">
                      <div class="card bg-transparent border-0">
                        <div class="car-body text-center">
                          <img src="{{hazard.geohazard_img.url}}" height="200" width="300">
                        </div>
                      </div>
                      
                    </div>
                    <div class="col-md-8 col-sm-12 mt-4" style="display: grid;place-items:center;">
                      <div class="card bg-transparent border-0">
                        <div class="car-body">
                          <h4>{{hazard.date_published}}</h4>
                          <p style="text-align:justify;">{{hazard.geohazard_info}}</p>
                        </div>
                      </div>
                    </div>
                  </div>
                {% endfor %}
                <hr>

template-with-labels.png

多年来一直致力于此,并期待着任何能够提供帮助的人.真正渴望在项目截止日期前找到解决方案的人就在我们家门口.提前感谢!

推荐答案

您应该能够通过其related_name访问相关的GeoHazardAssessment对象:

{% for history in histories %}
    {{ history.barangay_name}
    {# other history information #}

    {% for hazard in history.geohazards.all %}
        {{ hazard.geohazard_info }}
        {# other hazard information #}
    {% endfor %}

   {% for assessment in history.assessment.all %}
        {{ assessment.purok_name }}
        {# other assessment information #}
    {% endfor %}
{% endfor %}

访问related_name定义的属性将返回RelatedManager的一个实例,该实例具有类似all()的方法(与模型上的objects相同).

请注意,要做到这一点,您不需要在上下文中添加任何其他内容,但从性能Angular 来看,使用prefetch_related()可能是有意义的,否则对于每History个实例,将执行额外的查询来获取相关对象.

class HistoryView(ListView):
   model = History
   template_name = 'auxiliary/history.html'
   context_object_name = 'histories'
   paginate_by = 1


   def get_queryset(self):
       histories = super().get_queryset()
       histories = histories.prefetch_related("geohazards", "assessment")
       return histories

Django相关问答推荐

Django、htmx删除记录并更新

批量删除多对多条目?

Django OneToOneFieldto抽象对象

我如何告诉Django如何恢复自定义迁移?

Django基于查询集动态筛选字段名称

Django中的InvalidOperation错误[]

Django 模型 Select - 只允许管理界面上的特定转换

Django - 是否可以为查询集预取单个字段的多个过滤器?

带有代码完成功能的 python / django 的 Sublime Text 2 和 3 设置

Django ModelForm 没有指定模型类

我的 django 模型 DateField 如何将 30 天添加到提供的值?

如何在django中生成临时文件然后销毁

Django - 如何从模型中 Select 特定列?

Django 1.7 - 如何 suppress (1_6.W001)某些元素单元测试可能无法按预期执行.?

Django 应用程序运行良好,但收到 TEMPLATE_* 警告消息

具有 2 种语言的 Django 站点

Django 在视图之间传递数据

在 django admin 中控制 TextArea 小部件的大小

django.db.utils.OperationalError 无法连接到服务器

Django 将多个模型传递给一个模板