You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django模板中如何正确判断citizen.nizo.name与category.name相等?

Django模板中外键关联字段的判断逻辑修正

问题描述

我需要在模板中实现判断逻辑{% if citizen.nizo.name == category.name %},但当前使用i.nizo.name无法正常生效,希望让citizen.nizo.name == category.name的判断正确执行。

相关代码

one_category.html(当前模板代码)

{% for i in citizen %}
{% if  i.nizo == category.name %}
<p>if</p>
    <a href="{% url 'citizen' i.slug %}"><h3> {{ i.name }} - haqida malumuot</h3> </a> <br>
{% else %}
<p>else</p>

{% endif %}
{% endfor %}

models.py(模型定义)

from django.db import models
from django.urls import reverse

class Citizen(models.Model): 
    name = models.CharField(max_length=255, verbose_name="F.I.SH", blank=True, null=True)
    tugilgan_sanasi = models.DateField(verbose_name="Tug'ilgan sanasi", blank=True, null=True)
    slug = models.SlugField(max_length=255, unique=True, verbose_name="Slug")
    yashash_manzili = models.CharField(max_length=240, verbose_name="Yashah manzili", blank=True, null=True)
    content = models.TextField(verbose_name="Текст статьи", blank=True)
    photo = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Izoh", blank=True, null=True)
    is_published = models.BooleanField(verbose_name="Organilgan/Organilmagan")
    time_create = models.DateTimeField(auto_now_add=True, verbose_name="Время создания", blank=True, null=True)
    time_update = models.DateTimeField(auto_now=True, verbose_name="Время изменения", blank=True, null=True)
    nizo_shaxs = models.CharField(max_length=240, verbose_name="Nizoloshyatgan Shaxs F.I.SH", blank=True, null=True)
    nizo = models.ForeignKey('Category', on_delete=models.PROTECT, null=True, blank=True, verbose_name="Nizo не выбрана")
    mah = models.ForeignKey('Mahalla', on_delete=models.PROTECT, null=True, blank=True, verbose_name="Mahalla не выбрана")
        
    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('iib:citizen', kwargs={'citizen_slug': self.slug})

class Category(models.Model):
    name = models.CharField(max_length=100, db_index=True, verbose_name="Nizo")
    slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL")

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('iib:category', kwargs={'nizo_slug': self.pk})

    class Meta:
        verbose_name = 'Nizo'
        verbose_name_plural = 'Nizo'

views.py(视图函数)

from django.shortcuts import render, get_object_or_404
from .models import Citizen, Category

def show_one_category(request, nizo_slug: str):
    citizen = Citizen.objects.all()
    category = get_object_or_404(Category, slug=nizo_slug)
    context = {
        'category': category,
        'citizen': citizen,
    }
    return render(request, 'main/one_category.html', context)

问题分析与解决方案

1. 修正模板中的判断条件

当前模板里的{% if i.nizo == category.name %}是错误的:i.nizo是Category对象,而category.name是字符串,两者无法直接相等匹配。需要改成以下两种方式之一:

方式一:比较关联对象的name字段

{% for i in citizen %}
{% if i.nizo and i.nizo.name == category.name %}
<p>if</p>
    <a href="{% url 'citizen' i.slug %}"><h3> {{ i.name }} - haqida malumuot</h3> </a> <br>
{% else %}
<p>else</p>
{% endif %}
{% endfor %}
  • 增加i.nizo的判断是为了处理nizo字段为null的情况,避免模板报错。

方式二:直接比较Category对象(更高效准确)

因为视图中已经获取了当前的category对象,直接比较对象实例可以避免名称重复的问题:

{% for i in citizen %}
{% if i.nizo == category %}
<p>if</p>
    <a href="{% url 'citizen' i.slug %}"><h3> {{ i.name }} - haqida malumuot</h3> </a> <br>
{% else %}
<p>else</p>
{% endif %}
{% endfor %}

2. 优化视图查询(可选但推荐)

当前视图中Citizen.objects.all()会导致每次循环i.nizo时都发起一次数据库查询(N+1查询问题),可以用select_related预取关联的Category数据:

def show_one_category(request, nizo_slug: str):
    category = get_object_or_404(Category, slug=nizo_slug)
    # 预取关联的Category,减少数据库查询次数
    citizen = Citizen.objects.select_related('nizo').all()
    context = {
        'category': category,
        'citizen': citizen,
    }
    return render(request, 'main/one_category.html', context)

内容的提问来源于stack exchange,提问作者Rokki Khazratov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 00:15:37