我使用的是django rest框架,在使用counter()函数的行中,有一个post api面临速度问题。
@api_view(["POST"])
def calculate_stuff(request):
t1 = time.time()
machine_type = request.data['machine_type']
machine_nos = Machine.objects.filter(machine_type=machine_type).values_list('machine_no', flat=True)
query = Performance.objects.filter(Q(power=100) | Q(power=192),machine_no__in=machine_nos,
).values_list("machine_no", "power")
t2 = time.time()
print t2 - t1 # is around 0.2 seconds
count_192_100 = Counter(query)
t3 = time.time()
print t3 - t2 # is around 1.3 seconds
模型如下:
class Machine(models.Model):
machine_type = models.CharField(null=True, max_length=10)
machine_no = models.IntegerField(null=True)
store_code = models.IntegerField(null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now = True)
class Performance(models.Model):
machine_no = models.IntegerField(null=True)
power = models.IntegerField(null=True)
store_code = models.IntegerField(null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
此项目正在生产中运行,由于某些原因,两个模型之间没有使用foreignkey。我想在这里实现的是首先:从某个机器类型的“机器”模型中获取机器编号。第二:我想知道在“性能”模型中,每台机器的功率为100,功率为192的次数。
其他信息:我正在使用django 1.11、python 2.7.10、postgresql。