Bea
Bea

Reputation: 278

How to get the id using a get_context_data?

I would like to get the total amount of followers attached to the models using in models :

class Project(models.Model):
    owner = models.ForeignKey(User, related_name='project_created_by', on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    description = models.TextField(max_length=150, blank=True, null=True)
    followers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True)
    created = models.DateTimeField(auto_now_add=True)
    last_modefied = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

Here is the class

class ProjectListView(ListView):
    template_name = 'projectmanagement/project.html'
    context_object_name = 'projects'

    def get_queryset(self):
        queryset = Project.objects.filter(owner=self.request.user).order_by("name")
        return queryset

    def get_context_data(self, *args, **kwargs):
        context = super(ProjectListView, self).get_context_data(*args, **kwargs)
        project = Project.objects.get(pk=12) <-- HERE -->
        context['followers'] = project.followers.filter(followers=project).count()
        return context

Upvotes: 1

Views: 838

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

You can .annotate(..) [Django-doc] the queryset of your Product with the number of followers:

from django.db.models import Count

class ProjectListView(ListView):
    model = Project
    template_name = 'projectmanagement/project.html'
    context_object_name = 'projects'

    def get_queryset(self):
        return super().get_queryset().annotate(
            nfollowers=Count('followers')
        ).filter(
            owner=self.request.user
        ).order_by('name')

Now all projects in the context data will have an extra attribute nfollowers with the number of followers.

You can thus render this for example with:

{% for project in projects %}
    {{ project.name }}, followers: {{ project.nfollowers }}<br>
{% endfor %}

Upvotes: 1

Related Questions