如何对与ForeignKey Django关联的对象进行分类

时间:2017-12-26 05:17:44

标签: django foreign-keys

我有两个模型类

class Category(models.Model):
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Site(models.Model):
    name = models.CharField(max_length=200)
    category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True)
    link = models.CharField(max_length=200)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)


    def __str__(self):
        return self.name

因此,在模板中,我想将具有相同类别的网站分类(放在一起)。因为在主页上会有与所有类别的链接

            {% for category in category_list %}
            <li><a href="">{{ category.name }}</a></li>
            {% endfor %}

当您点击某个类别的链接时,会显示具有相同类别的网站。我该怎么做?

2 个答案:

答案 0 :(得分:0)

views.py

from django.views.generic import ListView

class SiteView(ListView):
    template_name = 'site.html'
    context_object_name = 'site_list'
    paginate_by = 8

    def get_category(self):
        category_id = self.request.GET.get('category', '')
        if category_id:
            try:
                category = Category.objects.get(id=category_id)
            except ObjectDoesNotExist:
                category = None
        else:
            category = None
        return category

    def get_queryset(self):
        category = self.get_category()
        if category:
            return Site.objects.filter(category=category).all()
        else:
            return Site.objects.all()

urls.py

   url(r'^site/$', SiteView.as_view(), name='site'),

模板

        {% for category in category_list %}
            <li><a href="{% url 'site' %}?category={{ category.id }}">{{ category.name }}</a></li>
        {% endfor %}

答案 1 :(得分:0)

views.py

from django.shortcuts import get_list_or_404, get_object_or_404

def category_view(request):
    category_list = get_list_or_404(Category)
    context = {'category_list': category_list}
    return render(request, '-your_templates-/category.html', context)

def site_view(request, cat_id):
    category = get_object_or_404(Category, pk=cat_id)
    context = {'category': category}
    return render(request, '-your_templates-/site.html', context)

urls.py

url(r'^category/$', views.category_view, name='category'), 
url(r'^category/(?P<cat_id>[0-9]+)/$', views.site_view, name='site'),

category.html

{% for category in category_list %}
    <li><a href="{% url 'app_name:site' category.id %}">{{ category.name }}</a></li>
{% endfor %}

我希望这会有所帮助。