2012-05-30 139 views
5
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轴上的所有饮料。我正在努力的主要事情是什么来查询我可以通过我可以循环的模板。思考?Django创建报告

+0

我遇到了类似的,但稍微简单一些的场景,我需要在Y上的日期和在X上的类别。解决它与一些相当残酷的数据传输。 +1,有兴趣看看是否有一个好的解决方案。 – Endophage

+0

顺便说一句@jasongonzales,你在哥伦比亚大学工作吗? –

+0

不在哥伦比亚,好笑,你为什么问? – jasongonzales

回答

2

你不能让他们在一个查询中,但是你可以让类似的东西(不想建立一个整体ENV测试,所以用它作为线索,而不是一个有效的解决方案):

# 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') 

为了得到一个严肃的PERF提升。

+0

所以,只需要清楚,因为我正在写一个Django模板,所以我可能应该将这些值替换为一个字典,而不是实际打印它们,是的? – jasongonzales

+0

除了.order_by('name')',你可以在模板中完成所有这些。只需松开括号并使用{{value}}在HTML代码中打印一个值。 –