2013-08-16 57 views
0

我希望在我的查询中包含来自其他表的列。 我希望在报告中包含来自报告的所有列和来自产品和制造商的名称列。包含来自其他模型的列的Django 1.5查询

我当前的查询看起来是这样的:

latest = Report.objects.values('date').latest('date')['date'].strftime('%Y-%m-%d')`] 
rows = Report.objects.filter(date=latest).order_by('platform') 

-

# 
class Manufacturer(models.Model): 
id = models.AutoField(primary_key=True) 
name = models.CharField(blank=False,null=False,unique=True,max_length=100) 
comment = models.CharField(blank=True,null=True,max_length=200) 
def __unicode__(self): 
    return u'%s' % self.name 

# 
class Product(models.Model): 
id = models.AutoField(primary_key=True) 
name = models.CharField(blank=False,null=False,unique=True,max_length=100) 
manufacturer = models.ForeignKey(Manufacturer,related_name="products",null=True,blank=True) 
comment = models.CharField(blank=True,null=True,max_length=200) 
timestamp = models.DateTimeField(auto_now_add=True) 
def __unicode__(self): 
    return u'%s' % self.name 

# 
class Part(models.Model): 
id = models.AutoField(primary_key=True) 
name = models.CharField(blank=False,null=False,unique=True,max_length=100) 
product = models.ForeignKey(Product,related_name="parts",null=True,blank=True) 
comment = models.CharField(blank=True,null=True,max_length=200) 
timestamp = models.DateTimeField(auto_now_add=True) 
def __unicode__(self): 
    return u'%s' % self.name 

# 
class Platform(models.Model): 
id = models.AutoField(primary_key=True) 
name = models.CharField(blank=False,null=False,unique=True,max_length=100) 
comment = models.CharField(blank=True,null=True,max_length=200) 
timestamp = models.DateTimeField(auto_now_add=True) 
def __unicode__(self): 
    return u'%s' % self.name 

# 
class Report(models.Model): 
id = models.AutoField(primary_key=True) 
part = models.ForeignKey(Part,related_name="reports") 

回答

1

你不需要在你的QuerySet中包含那些元素。事实上,你已经拥有了它们:你只需要检索相关对象

与您的代码,最新报告模型查询集这对部分模型外键

# in any *.py files, such as views.py 
for report in rows: 
    # You can access the Part object, so you can access Product, 
    # so you can access Manufacturer, just by hooking through the reverse relationship 
    product_name = report.part.product.name 
    manufacturer_name = report.part.product.manufacturer.name 

你可以从你的模板过访问这些元素:

# in your template.html 
{% for report in rows %} 
<p>Part: <span>{{ report.part }}</span></p> 
<p>Product: <span>{{ report.part.product.name }}</span></p> 
<p>Manufacturer: <span>{{ report.part.product.manufacturer.name }}</span></p> 

所以,你可以看到,一切都已经与y我们的查询集。

+0

正是我所需要的......将row.part.product.name/row.part.product.manufacturer.name放入模板中,正是我所需要的。谢谢。 –

0

您可以通过使用report.part.product.namereport.part.product.manufacturer.name的报告获得产品和制造商名称。

所以,你可以做(​​使用当前查询):

for report in rows: 
    product_name = report.part.product.name 
    manufacturer_name = report.part.product.manufacturer.name 

有更好的方法去做,但是这取决于你想用的名字做的,所以你需要一个什么如果你想在那里获得帮助,那么它就更具体一点如果您确实最终使用了一个简单的for循环,那么您可能需要查看select_related以避免为rows中的每个报告引发额外查询。

相关问题