Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Count All Objects of a Database Table in Django?

I have a model as below, I would like to filter a user's all work_times in Table Work with Django 2.0.4, thanks in advance for any advice.

class Work(models.Model):
    name = models.CharField(max_length=800)
    date = models.DateField(auto_now=False, null=True, blank=True)
    time = models.TimeField(auto_now=False, null=True, blank=True)
    work_times = models.FloatField(default=1, verbose_name="work times(hours)")
    user = models.ManyToManyField(User, related_name="works", blank=True)
like image 883
Elsa Avatar asked Oct 23 '25 07:10

Elsa


2 Answers

You can get all of them by using:

all_work = Work.objects.filter(user=sample_user)

and if you want to know the number of rows in that query you can user:

all_work_count = Work.objects.filter(user=sample_user).count()

You can access each item of that query by:

for each_work in all_work:
    print(each_work.work_times)

Edit

By getting all works of a user, you can access the individual work_time from the work instance. However, you can access the work_times this way as well:

all_work = Work.objects.filter(user=sample_user).values('work_times')

This will give you only the work_times. But this way, you cannot know what work_time belongs to which work.

Edit 2
To get the total time of work, you have two options, the simple and somewhat more complex:

Easy one

This is the technically easy solution, but is usable only for very small query size.
all_works = Work.objects.filter(user=sample_user)
total_work = 0
for work in all_works:
    total_work += work.work_times

Complex one

Although this one is much more efficient and is in one line, you might have to play with it a bit to get it right.

from django.db.models import Sum

total_works = Work.objects.filter(user=sample_user).aggregate(Sum("work_times"))
like image 162
Ramtin Avatar answered Oct 25 '25 20:10

Ramtin


count=User.objects.filter(username='username').first().work_set.all().count()

like image 29
Susaj S N Avatar answered Oct 25 '25 21:10

Susaj S N