0

How can I count the fields of All Objects in a Database Table by date in Django?

For example: I can access the number of all records of my model named "MateryalEkle" with this code below {{materyalIstatistik}}.

But I want to reach the count of all fields separately. And I want to do them by date range i.e. weekly, monthly and yearly.

for example: how many "TELEFON", how many "SIM KART", how many "SD KART".

and I want to filter these count by date range.

for example : 01.03.2021 - 07.03.2021 or 01.01.2021 -.01.01.2022

How can I do that? Thanks for your help.

models.py

 class MateryalEkle(models.Model):
       
        MATERYALCINSI = [
        ('TELEFON', 'TELEFON'),
        ('SIM KART', 'SIM KART'),
        ('SD KART', 'SD KART'),
        ('USB BELLEK', 'USB BELLEK'),
    ]

        materyalMarka = models.CharField(max_length=50, verbose_name='MATERYAL MARKA', blank=True, null=True, default="-")
        cinsi = models.CharField(max_length=50, choices=MATERYALCINSI, verbose_name='MATERYAL CİNSİ', blank=True, null=True, default="-")
        gelisTarihi = models.DateTimeField(auto_now_add=True)
        slug = AutoSlugField(populate_from='materyalMarka', unique=True, blank=True, null=True)

        def __str__(self):
            return self.materyalMarka

views.py

def istatistik(request): materyalIstatistik = MateryalEkle.objects.all().count()

return render(request, 'delil/istatistikler.html', {'materyalIstatistik':materyalIstatistik})

istatistikler.html

`<p>materyal : {{materyalIstatistik}} </p>`
sefaseker
  • 33
  • 3
  • You'll want to filter your queryset by those dates and then use [aggregation](https://docs.djangoproject.com/en/3.1/topics/db/aggregation/) against it to get counts by field value. I don't know if [this old answer](https://stackoverflow.com/a/3606466/833881) is still valid, but it should point you in the right direction. – kungphu Mar 12 '21 at 03:00

1 Answers1

0

you can just filter by the field gelisTarihi using gt and lt also you can specify by year and month example:

 materyalIstatistik = MateryalEkle.objects.filter(gelisTarihi__year__lt=2020).count()

this will give you all the instances count before 2020 you can be more specific and set a specific date and filter your queryset hope that this can be helpful

ladhari
  • 505
  • 4
  • 15