gpt4 book ai didi

python - Django 创建报告

转载 作者:太空狗 更新时间:2023-10-30 01:30:01 26 4
gpt4 key购买 nike

class Beverage(models.Model):
name=models.CharField(max_length=255)

def __unicode__(self):
return self.name

class Location(models.Model):
name=models.CharField(max_length=255)
beverages = models.ManyToManyField(Beverage, through='LocationStandard')
location_number=models.CharField(max_length=255)
organization=models.CharField(max_length=255)

def __unicode__(self):
return self.name

class LocationStandard(models.Model):
beverage=models.ForeignKey(Beverage)
location=models.ForeignKey(Location) #elim this or m2m
start_units=models.IntegerField()
fill_to_standard=models.IntegerField(max_length=10)
order_when_below=models.IntegerField(max_length=10)

class Order(models.Model):
location=models.ForeignKey(Location) #elim this or m2m
beverage=models.ForeignKey(Beverage)
units_ordered=models.IntegerField(max_length=10, default=0)
order_delivered=models.BooleanField(default=False)
timestamp=models.DateTimeField(auto_now_add=True)
user=models.ForeignKey(User)

我如何生成一份报告,该报告将为我提供一个 HTML 表格,其中 x 轴为所有位置,而 y 轴为所有饮料。我正在苦苦挣扎的主要事情就是要查询什么我可以传递我可以循环的模板。想法?

最佳答案

你不能在一个查询中得到它们,但你可以做类似的事情(不想设置整个环境来测试,所以把它作为一个线索,而不是一个可行的解决方案):

# you can't do order_by in a template, either do them in the view, or 
# make methods in the model, or make it the Meta default ordering

# print the header, and make sure we got a list of all beverage cached
beverages = Beverage.objects.order_by('name')
for beverage in beverages:
print each cell of your header

# print a row for each location
locations = Location.objects.all()
for location in locations:
print the location name table cell
location_beverages = iter(location.beverages.order_by('name'))
# for each beverage, we print a cell. If the beverage is in the
# location beverage list, we print a checked cell
# we use the fact that queryset are iterable to move the cursor
# only when there is a match
cur_bev = location_beverages.next()
for beverage in beverages:
if beverage == cur_bev:
print checked table cell
cur_bev = location_beverages.next()
else:
print empty table cell

存储查询集的中间变量非常重要,因为它们可以让您从 Django 查询集缓存中受益。

使用 Django 1.4 或更高版本,您可以替换:

locations = Location.objects.all()

通过:

locations = Location.objects.prefetch_related('beverages')

获得显着的性能提升。

关于python - Django 创建报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10808505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com