简体   繁体   English

如何根据Django中的模型对sql输入进行分类

[英]how to categorize sql inputs according to models in django

I want to learn django and I should categorize my sql inputs according to my models. 我想学习django,我应该根据自己的模型对sql输入进行分类。

For example I have some models like this: 例如,我有一些这样的模型:

class Author(models.Model):
    authorName = models.CharField(max_length=30)

    def __str__(self):
        return self.authorName


class Book(models.Model):
    author = models.ForeignKey(Authors, on_delete=models.CASCADE)
    bookName = models.CharField(max_length=60)
    downloadLink = models.FileField()
    downloadCount = models.IntegerField(default=0)

    def __str__(self):
        return self.bookName

and I want to an output in my .html file like this; 我想要这样在我的.html文件中输出;


Sherlock Holmes 夏洛克·福尔摩斯

  • A Study in Scarlet 血字的研究
  • The Sign of the Four 四个标志
  • The Hound of the Baskervilles 巴斯克维尔的猎犬

Suzanne Collins 苏珊·柯林斯(Suzanne Collins)

  • The Hunger Games 饥饿游戏
  • Catching Fire 着火
  • Mockingjay 莫金杰

I tried this code in my html file but it doesn't work 我在html文件中尝试了此代码,但是它不起作用

<ul>
  {% for author in all_authors %}

      <h2>{{ author.authorName }}</h2>

      {% for book in all_books %}
          {% if book.author == author.authorName %}

              <li><a href="{{ book.downloadLink.url }}" download="{{ book.downloadLink.url }}">{{ book.bookName }}</a></li>

          {% endif %}
      {% endfor %}

  {% endfor %}
</ul>

My output is; 我的输出是;


Sherlock Holmes 夏洛克·福尔摩斯

Suzanne Collins 苏珊·柯林斯(Suzanne Collins)


Here is my view.py file; 这是我的view.py文件;

def books(request):
    return render(request,'../templates/library/library-template.html', {
        'all_authors': Author.objects.all(),
        'all_books': Book.objects.all(),
    })

How can I fix it? 我该如何解决? Or are there any different solution for fix this? 还是有其他解决方案来解决此问题?

Thank you.. :) 谢谢.. :)

Your if statement will never be true, you are comparing an object and a string 您的if语句永远不会为真,您正在比较一个对象和一个字符串

      {% if book.author == author.authorName %}

So you could change this to 所以你可以将其更改为

      {% if book.author == author %}

But this is still wasteful, you can just use the reverse lookup so you won't need the if statement at all 但这仍然很浪费,您可以使用反向查找,因此根本不需要if语句

<ul>
  {% for author in all_authors %}

      <h2>{{ author.authorName }}</h2>

      {% for book in author.book_set.all %}

              <li><a href="{{ book.downloadLink.url }}" download="{{ book.downloadLink.url }}">{{ book.bookName }}</a></li>
      {% endfor %}

  {% endfor %}
</ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM