I'm working with a project that has 3 models.
Now I want to know how much data have come me today.
In my view I have this,
def dataPlots(request):
today = datetime.date(2020, 5, 18)
data = DevData.objects.filter(data_timestamp__date=today)
data = loads(serializers.serialize('json', data))
If I use len()
I can now the total value. But how can I know how much data do I have for each fleet?
I have come to create this loop that would tell me for each device, but what I need is the value for each fleet and furthermore I think I am getting complicated.
data_dict = {}
for d in data:
if d['fields']['dev_eui'] in data_dict:
data_dict[d['fields']['dev_eui']] = data_dict[d['fields']['dev_eui']] + 1
else:
data_dict[d['fields']['dev_eui']] = 1
print(data_dict)
The models are:
class Fleet(models.Model):
fleet_id = models.IntegerField(primary_key=True, unique=True)
fleet_name = models.CharField(max_length=20, unique=True)
class Device(models.Model):
dev_eui = models.CharField(max_length=16, primary_key=True, unique=True)
dev_name = models.CharField(max_length=20, unique=True)
fleet_id = models.ForeignKey(Fleet, on_delete=models.CASCADE)
def __str__(self):
return self.dev_eui
class DevData(models.Model):
data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False)
data_timestamp = models.DateTimeField()
data = models.FloatField()
dev_eui = models.ForeignKey(Device, on_delete=models.CASCADE)
def __str__(self):
return self.dev_eui
Can somebody help me? I imagine that combining two models and some filter should suffice, but I don't know how to do it.
You can annotate the Fleet
s with the given amount of data, for example:
from django.db.models import Count
Fleet.objects.filter(
device__devdata__data_timestamp__date=today
).annotate(
total_data=Count('device__devdata')
)
The Fleet
objects that arise from this queryset will have an extra attribute .total_data
that contains the total amount of data for today
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments