A
A
Alexey Sergeev2016-03-06 01:40:19
Django
Alexey Sergeev, 2016-03-06 01:40:19

Fetching data from the database. QuerySet?

Hello!
The crux of the matter is as follows. I'm trying to write a simple application to collect the number of workers on objects. There are
models

class SObjects(models.Model):
  title = models.CharField(max_lenght=128)

class Subpodr(models.Model):
  sobj = models.ForeignKey(SObjects)
  name = models.CharField(max_lenght=128)

class Peoples(models.Model):
  sobj = models.ForeignKey(SObjects)
  subpodr = ForeignKey(Subpodr)
  date = models.DateField(default=datetime.datetime.today())
  rab = models.IntegerField(default = 0)

Accordingly, SObjects is a model with a description of the objects on which people work.
Subpodr - subcontracting organizations (There can be several organizations at one facility)
Peoples - a model that collects the number of workers.
On the web page I want to display as follows.
On the main page in the form of a table with dates and the sum of workers for the object for each day.
When you click on an object, a list with contractors and number by date.
The question is how to return a dictionary from the database with (data will always be selected for a month)
{Date : {Object 1: {Contractor 1: Number of Workers, Contractor 2: Number of Workers}}, Date 2 ....}
Or in in any other convenient way.
I think you need to look in the direction of either annotate, aggregate or pure sql (extra)
Wrote a function that counts the sum of people by 1 object for a certain day
def calc(sobj, date):
  return Peoples.objects.filter(date=date, sobj=sobj).aggregate(Sum('rab'))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oscar Django, 2016-03-06
@SergeevAI

If I remember correctly:

class Peoples(models.Model):
  subpodr = ForeignKey(Subpodr)
  date = models.DateField(default=datetime.datetime.today())
  rab = models.IntegerField(default = 0)
  class Meta:
    unique_together = ('subpodr', 'date')

peoples_for_main_page = Peoples.objects.values('subpodr__sobj', 'date', 'rab').annotate(
  num_peoples=Sum('rab')).order_by('date', 'subpodr__sobj')

sobject = Sobject.objects.get(pk=current_sobject_pk)
peoples_for_sobject_page = Peoples.objects.filter(subpodr__sobj=sobject).annotate(
  num_peoples=Sum('rab')).order_by('date', 'subpodr')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question