如何使用django orm获取与sql查询等效的数据:
SELECT *
FROM "financeDocuments_documenttemplateline"
LEFT JOIN "financeDocuments_documentinstanceline" ON "financeDocuments_documentinstanceline".template_line_id = "financeDocuments_documenttemplateline".id AND "financeDocuments_documentinstanceline".document_instance_id = 1
WHERE "financeDocuments_documenttemplateline".document_type_id = 1
我用:
document_lines = DocumentTemplateLine.objects.filter(document_type__id = document_instance.document_type.id).select_related('documentinstanceline').values('documentinstanceline__value')
但它会产生:
SELECT "financeDocuments_documentinstanceline"."value" FROM "financeDocuments_documenttemplateline" LEFT OUTER JOIN "financeDocuments_documentinstanceline" ON ("financeDocuments_documenttemplateline"."id" = "financeDocuments_documentinstanceline"."template_line_id") WHERE "financeDocuments_documenttemplateline"."document_type_id" = 1
模型就像这样:
class DocumentInstance(models.Model):
company = models.ForeignKey(Company)
period = models.ForeignKey(Period, verbose_name=u'период')
document_type = models.ForeignKey(DocumentType, verbose_name=u'вид документа' )
created = models.DateTimeField('created', auto_now_add=True)
author = models.ForeignKey(User)
class Meta:
unique_together= (('company', 'period', 'document_type'),)
class DocumentInstanceLine(models.Model):
document_instance = models.ForeignKey(DocumentInstance, related_name='lines')
template_line = models.ForeignKey(DocumentTemplateLine)
value = models.FloatField(default=0.00)
comment = models.TextField(blank=True)
class Meta:
unique_together= (('document_instance', 'template_line'),)
如何更改django orm的代码以添加第二个条件,就像我的第一个SQL查询一样?