首页 > 解决方案 > 将动态查询集传递给 Django 模板

问题描述

我正在尝试根据是否存在特定“注释类型”的注释, 将动态查询集从views.py我的 django 模板 ( ) 传递。 我有一个与“公司”模型相关的“笔记”模型,如图所示:company_detail.html示例图像

models.py

class Company(models.Model):
    family = models.ForeignKey(Family, on_delete=models.CASCADE)
    type = models.ForeignKey(Type, models.CASCADE)
    name = models.CharField(max_length=200)
    phone = PhoneField(blank=True)
    email = models.EmailField(blank=True, max_length=100)
    address = AddressField(null=True, blank=True, on_delete=models.CASCADE)
    history = HistoricalRecords()

class Notes(models.Model):
    NOTE_CHOICES = [
        ('sales_structure', 'Sales Structure'),
        ('product_prefs', 'Product Preferences'),
        ('personnel', 'Personnel'),
        ('misc', 'Miscellaneous')
    ]
    account = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='notes')
    note_type = models.CharField(max_length=50, choices=NOTE_CHOICES)
    note_text = models.TextField(max_length=300)
    history = HistoricalRecords()

我的观点使用django.views.generic.base.View如下:

views.py

class CompanyDetail(View):

    def get(self, request, *args, **kwargs):
        company = get_object_or_404(Company, pk=self.kwargs.get('pk'))
        contact_table = ContactTable(Contact.objects.filter(account=self.kwargs.get('pk')))
        notes = Notes.objects.filter(account=self.kwargs.get('pk'))
        note_types = []
        for type in Notes.NOTE_CHOICES:
            text = type[1]
            notes_sub = notes.filter(note_type=type[0])
            quant = notes_sub.count()
            if quant > 0:
                note_types.append((text, quant, notes_sub))
        notes_form = NoteForm(account=company)
        return render(request,
            'companies/company_detail.html',
                {'company': company,
                 'notes': notes,
                 'note_types': note_types,
                 'note_form': notes_form,
                 'contact_table': contact_table
                 },
        )

传递给模板:

<h3>Account Notes</h3>
        <div class="accordion" id="NotesAccordion">
            {% for type in note_types %}
                <div class="card">
                    <div class="card-header" id=Heading_{{ type.0 }}>
                        <h2 class="mb-0">
                            <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target=#{{ type.0 }} aria-expanded="false" aria-controls={{ type.0 }}>
                                {{ type.0 }} ({{ type.1 }})
                            </button>
                        </h2>
                    </div>
                    <div id={{ type.0 }} class="collapse" aria-labelledby=heading_{{ type.0 }} data-parent="#NotesAccordion">
                      <div class="card-body">
                          {% for note in {{ type.3 }} %}
                          
                          {% endfor %}
                      </div>
                    </div>
                </div>
            {% endfor %}
        </div>

我希望有很多<div class="card">'s,因为有使用的主题,目前正在工作,但不工作的是只显示每个相应的注释<div class="card-body">

{% for note in {{ type.3 }} %}是问题所在。谁能建议另一种方法来实现这一点?我希望它是动态的,这样我就不必重新编写我的笔记views.py,并且company_detail.html我的笔记选择在任何时候都会发生变化。

标签: pythonhtmldjangodjango-viewsdjango-templates

解决方案


所以我能够通过使用自定义包含模板标签来实现这一点,这只是几行额外的代码。


推荐阅读