模板中的django查询集

时间:2017-11-18 23:57:54

标签: python django django-models django-templates django-views

我试图通过使用一些模型输入字段来进行特定查询。 我有以下模型条目:

models.py

class Work(models.Model):

    categories =(
                ('cat1', 'cat1'),
                ('cat2', 'cat2'),
                ('cat3', 'cat3'),
                ('cat4', 'cat4'),
                ('cat5', 'cat5'),
                )
    title = models.CharField(max_length=200)
    description = RichTextUploadingField(config_name='awesome_ckeditor')
    date = models.DateTimeField(default=timezone.now)
    category = models.CharField(max_length=200, choices = categories, default = 'projects')
    thumb = models.ImageField(upload_to = 'works/thumbs', blank = True)
    content = models.FileField(upload_to = 'works/content_media', blank = True)
    published = models.BooleanField()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("work_detail",kwargs={'pk':self.pk})
    @property
    def thumb_url(self):
        if self.thumb and hasattr(self.thumb, 'url'):
            return self.thumb.url
    @property
    def content_url(self):
        if self.content and hasattr(self.content, 'url'):
            return self.content.url

这是视图:

views.py

class WorksListView(ListView):
    template_name = 'template.html'
    model = Work

    def get_queryset(self):
        return Work.objects.filter(published=True).order_by('-date')

我试图首先通过类别字段查询,然后通过以下模板中的条目进行查询:

template.html

{% for category in works_list.category %}
    <ul data-category-name={{category.name}}>
    {% for work in category.works %}
        <li data-thumbnail-path={{thumbnail.url}} data-url={{content.url}} >
            <div>
                <p class="gallery1DecHeader">{{work.title}}</p>
                <p class="gallery1DescP">{{work.description}}</p>
            </div>
        </li>
    {% endfor %}
{% endfor %}

我需要改变什么?

2 个答案:

答案 0 :(得分:0)

好的,我可以看到有一些问题。首先,尝试添加context_object_name = 'works_list'这样,您就可以将object_list称为works_list,就像在模板外部循环中一样。更大的问题是您正在迭代works_list.category,根据您的Work模型,Charlist()choices。我想你可能会对{% for category in works_list.category %} kwarg做了什么以及期望choices迭代你的categories以及给你Category中定义的猫的列表感到困惑。据我所知,这不是选择的工作方式。

如果您转到管理面板并为您的工作模型添加新条目,您会看到该类别有一个下拉列表,其中包含您的猫列表。因此,选项为新的Work对象定义了一组合法的类别选项,而不是现有Work对象中的列表。

我认为您真正想要的是另一个模型work = models.ForeignKey(Work, on_delete=models.CASCADE),它将Work定义为一对多关系。基本上,您希望Category具有可以迭代的#gardenA a = ....... b = ....... def moduleA(a,b): (function inside here) 个对象的子集。这将涉及重新设计您构建和访问数据的方式。

答案 1 :(得分:0)

您至少需要更改views.py和template.html。添加context_object_name和额外的上下文(Doc Link

<强> views.py

class WorksListView(ListView):
    template_name = 'template.html'
    model = Work
    context_object_name = 'work_list'

    def get_queryset(self):
        return Work.objects.filter(published=True).order_by('-date')

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(WorksListView, self).get_context_data(**kwargs)
        # Insert categories so that it can be used in template
        context['categories'] = Work.categories
        return context

<强> template.html

{% for category in categories%}
<ul data-category-name={{category.0}}>
    {% for work in work_list %}
        {% if category.0 == work.category %}
            <li data-thumbnail-path={{work.thumb_url}} data-url={{work.content_url}} >
                <div>
                    <p class="gallery1DecHeader">{{work.title}}</p>
                    <p class="gallery1DescP">{{work.description}}</p>
                </div>
            </li>
        {% endif %}
    {% endfor %}
</ul>
{% endfor %}
相关问题