gpt4 book ai didi

mysql - Django 1.5 查询包含来自其他模型的列

转载 作者:行者123 更新时间:2023-11-29 13:39:30 25 4
gpt4 key购买 nike

我希望在我的查询中包含其他表中的列。我希望在输出中包含报告中的所有列以及产品和制造商中的名称列。

我当前的查询如下所示:

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")

最佳答案

您实际上并不需要在查询集中包含这些元素。事实上,您已经拥有它们:您只需要检索相关对象

使用您的代码,最新报告模型上的查询集,它们在部分上有外键型号

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

正如您所看到的,所有内容都已随您的查询集一起提供。

关于mysql - Django 1.5 查询包含来自其他模型的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18278174/

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