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)
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:
all_works = Work.objects.filter(user=sample_user)
total_work = 0
for work in all_works:
total_work += work.work_times
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"))
count=User.objects.filter(username='username').first().work_set.all().count()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With