如何显示记录属于django中的类别

时间:2017-08-14 08:29:38

标签: python django

我有一个 models.py

from django.db import models
from django.utils import timezone


class Kategorie(models.Model):
    glowna = models.CharField(max_length=150, verbose_name='Kategoria')
    slug_kat = models.SlugField(max_length=255, verbose_name='Odnośnik', default='')

    class Meta:
        verbose_name='Kategoria'
        verbose_name_plural='Kategorie'

    def __str__(self):
        return self.glowna


class Witryna(models.Model):
    nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony')
    adres_www = models.CharField(max_length=70, verbose_name='Adres www')
    slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url', unique=True)
    email = models.CharField(max_length=100, verbose_name='Adres e-mail')
    text = models.TextField(max_length=3000, verbose_name='Opis strony')
    kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria')
    data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji')

    class Meta:
        verbose_name='Strona www'
        verbose_name_plural = 'Strony www'

    def publikacja(self):
        self.data_publikacji=timezone.now()
        self.save()

    def __str__(self):
        return self.nazwa

我创建了视图

def detale_kat(request, slug_kat):
konkretna_kategoria = Witryna.objects.annotate(cnt_witryna=Count('kategoria')).order_by('kategoria')
return render(request, 'firmy/detale_kat.html', {'konkretna_kategoria': konkretna_kategoria})

在html fil的最后我有一个django标签,如:

{% extends 'firmy/index3.html' %}
{% block kategoria %}
{%for konkret in konkretna_kategoria%}
{{ konkret.cnt_witryna }}
{% endfor %}
{% endblock %}

在我的主html文件的应用程序中,我查看了Kategorie类添加的56个类别。显示类别列表是详细视图。当我点击例如类别“商业”的链接时如何使用定义,并且我想显示在该类别中添加的所有网站。注释是一个很好的方法,或者我必须使用过滤器?

1 个答案:

答案 0 :(得分:1)

如果您想要过滤记录,请使用filter

在视图中:

def detale_kat(request, slug_kat):
    konkretna_kategoria = Witryna.objects.annotate(cnt_witryna=Count('kategoria')).order_by('kategoria')
    websites = Witryna.objects.filter(kategoria__slug_kat=slug_kat)
    return render(request, 'firmy/detale_kat.html', 
                  {'konkretna_kategoria': konkretna_kategoria, 
                  'websites': websites})

在html中:

...
{% for website in websites %}
    {{ website.nazwa }}
{% endfor %}
...