Home > Mobile >  Django Display count of database entries related via foreign key
Django Display count of database entries related via foreign key

Time:02-03

I have two models, ProjectNotes and ProjectNoteComments. ProjectNoteComments are related to ProjectNotes via a foreign key. I want to display the number of comments each note has on a listview. I am just learning Django and so far I have not been able to figure out how to retrieve and display the comment count.

My view:

(I do import count)

class ProjectNotesList(ListView):
    model = ProjectNotes
    template_name = 'company_accounts/project_notes.html'
    comments = ProjectNotes.comments

    def related_project(self, **kwargs):
        project = get_object_or_404(Project, id=self.kwargs.get('pk'))
        notes = ProjectNotes.objects.all
        return notes

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super().get_context_data(**kwargs)
        context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk'))
        return context

    commentscount = ProjectNotes.objects.annotate(num_comments=Count('comments'))

My template:

{% extends 'base.html' %}

  {% block content %}
  <div >
    <h1>Notes for {{ project }}</h1>
     {% if project.notes.all %}
     {% for note in project.notes.all %}
       <div class ="projectnotes-entry">
         
      <div >
       <div >
        <div >
          <div >
            <div ><a href="{% url 'project_note_detail' project.pk note.pk %}">{{ note.title }}</a></div>
            <div >{{ note.body | safe | truncatewords:"20"|linebreaks }}
            <a href="{% url 'project_note_detail' project.pk note.pk %}">read more</a></div>
         </div>
       </div>
      </div>
      </div>     
     </div>
     <h2>comments count</h2>
     {{ commentscount }}
     {% endfor %}
     {% else %}
     <p>No notes have been have been added yet.</p>
     {% endif %}
   </div>
  {% endblock content %}

The models:

class ProjectNotes(models.Model):
    title = models.CharField(max_length=200)
    body = tinymce_models.HTMLField()
    date = models.DateField(auto_now_add=True)
    project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes')

    def __str__(self):
        return self.title

class ProjectNoteComments(models.Model):
    body = tinymce_models.HTMLField()
    date = models.DateField(auto_now_add=True)
    projectnote = models.ForeignKey(ProjectNotes, default=0, blank=True, on_delete=models.CASCADE, related_name='comments')

CodePudding user response:

Short version:

{{ note.comments.all.count }}    # possibly works also without 'all' but can't check right now

I've just answered similar problem with simple explanation of relationships. https://stackoverflow.com/a/70955851/12775662

Read official docs, it's really rewarding. https://docs.djangoproject.com/en/4.0/topics/db/models/#relationships

  •  Tags:  
  • Related