如何在Django中使用ForeignKey字段作为过滤器?

2024-04-29 01:19:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两种型号:

class Category(models.Model):
    title = models.CharField(max_length=250)
    ### other fields

class Album(models.Model):
    category = models.ForeignKey(Category)
    subject = models.CharField(max_length=200)
    ### other fields...

是的。你知道吗

我刚刚写了一个按特定类别过滤相册的视图,我也想把它们都放进去主页.html模板:

#views.py
def commercial(request):
    commercial_subjects = Album.objects.filter(category__title__contains="commercial" )
    return render(request, 'gallery/index.html', {'commercial_subjects': commercial_subjects})

它只适用于商业领域。如果我想为每个类别编写多个视图,就像硬编码一样。我需要的是一个视图或过滤过程,显示所有类别及其相关的相册.主题自动地。所以最终结果必须是这样的:

Personal

  • ALBUM 1
  • ALBUM 2

Commercial

  • ALBUM 4
  • ALBUM5

我该怎么做?你知道吗


Tags: 视图fieldsalbummodeltitlemodels类别length
2条回答
#views.py
def commercial(request):
    commercial_subjects = Album.objects.filter(category__title="commercial")

这很简单。首先给外键一个related_name

class Album(models.Model):
    category = models.ForeignKey(Category, related_name='albums')

从视图传递所有类别:

def myView(request):
    categories = Category.objects.all()
    return render(request, 'gallery/index.html', {'categories': categories})

然后在模板中:

<ul>
    {% for category in categories %}
        <li>{{ category.title }}</li>
        {% with category.albums.all as albums %}
            {% if albums %}
                <ul>
                   {% for album in albums %}
                      <li>{{ album.subject }}</li>
                   {% endfor %}
                 <ul>
            {% endif %}
        {% endwith %}
    {% endfor %}
</ul>

相关问题 更多 >