template中引用外键值的处理

template变量中不能有空格,符号

models文件

class Article(models.Model):
    title = models.CharField(max_length=100, verbose_name='文章标题')


class Org(models.Model):
    name=models.CharField(max_length=30, verbose_name='公司名')


# 因为在博客项目中, 每个用户都是作者, 所以这里用author来表示用户
class Author(models.Model):
    username = models.CharField(max_length=30, verbose_name='用户名')
    articles_collected = models.ManyToManyField(to=Article, verbose_name='收藏的文章')
    org = models.ForeignKey(to=Org, on_delete=models.CASCADE, null=True)

例子1. 从机构中获取所有用户收藏的文章数

views
def orgs(request):
  orgs = Org.objects.all()
  for i in range(len(orgs)):
    # 这里的counts名称可以随意写,不过要和html循环中取的字段值一致,这里为{{ row.counts }}
    orgs[i].counts = orgs[i].author_set.all().values('articles_collected').count()

  return render(request, "web/show-org.html", locals())
html文件如下
<table class="table"  >
  <thead>
    <tr>
      <th>名称</th>
      <th>作者数量</th>
      <th>文章数</th>
    </tr>
  </thead>
  <tbody>
    {% for row in orgs %}
      <tr>
        <td>{{ row.name }}</td>
       
        <td>{{ row.author_set.all.count }}</td>

        <td>{{ row.counts }}</td>
      </tr>
    {% endfor %}

主要看文章数row.counts是怎么处理显示的

例子2,从Article中反向查找Author中的字段值

函数中查找方式为article1.author_set.all()[0].username

html文件
<div id="content">
  <div  style="padding-left: 25px; ">
    <table class="table"  >
    <thead>
      <tr>
        <th>文章名称</th>
        <th>作者</th>
        <th>机构</th>
      </tr>
    </thead>
    <tbody>
      {% for row in articles %}
        <tr>
          <td>{{ row.title }}</td>
         
          <td>{{ row.author_set.all.0.username }}</td>
  
          <td>{{ row.author_set.all.0.org }}</td>
  
        </tr>
      {% endfor %}
    </tbody>
    </table>
  </div>
</div>
posted @ 2022-11-18 11:48  坚强的小蚂蚁  阅读(19)  评论(0编辑  收藏  举报