Home > Enterprise >  Django - showing count of objects pointing to a key
Django - showing count of objects pointing to a key

Time:07-30

I have a list of job offers, and my problem is to list how many offers are in each job offer. For example

Offer: welder - we have 7 positions

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models import Count

STATUS = (
    (0,"Inactive"),
    (1,"Active")
)

class Offer_type(models.Model):
    type = models.TextField()

    class Meta:
        ordering = ['-type']

    def __str__(self):
        return self.type

class Offer_general(models.Model):
    offer_name = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True)
    status = models.IntegerField(choices=STATUS, default=0)
    type = models.ForeignKey(Offer_type, on_delete= models.PROTECT)

    class Meta:
        ordering = ['-id']

    def __str__(self):
        return self.offer_name

class Offer_localization(models.Model):
    localization = models.TextField()

    class Meta:
        ordering = ['-localization']

    def __str__(self):
        return self.localization

class Offer_details(models.Model):
    slug = models.SlugField(max_length=200, unique=True)
    localization = models.ForeignKey(Offer_localization, on_delete= models.PROTECT, default="Opole")
    fk_offer_general_id = models.ForeignKey(Offer_general, on_delete= models.PROTECT)
    updated_on = models.DateTimeField(auto_now= True)
    content = models.TextField()
    requirements = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=STATUS, default=0)

    class Meta:
        ordering = ['-id']

    def __str__(self):
        return self.slug

views.py

from django.shortcuts import render
from django.views import generic
from django.db.models import Count
from .models import Offer_general
from .models import Offer_details

# Create your views here.
class OfferGeneralList(generic.ListView):
    queryset = Offer_general.objects.filter(status=1).order_by('-id')
    template_name = 'index_offers.html'

    def counto(self):
        context = super().get_context_data(**kwargs)
        context['album'] = Offer_details.objects.filter(fk_offer_general_id=id).count()#this is where i tried to print it somehow
        return context

class OfferGeneralDetails(generic.DetailView):
    model = Offer_general
    template_name = 'offer_detail.html'

CodePudding user response:

Just use this query:

from django.db.models import Sum    
Offer_details.objects.values('fk_offer_general_id').annotate(sum=Sum('fk_offer_general_id')

It will return a QuerySet with dicts like

{ 'fk_offer_general_id': 'welder', 'sum': 7 }
  • Related