将原始SQL查询转换为Django orm [英] Convert raw sql query to django orm
本文介绍了将原始SQL查询转换为Django orm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用PostgreSQL编写了此查询,我对将此查询转换为Django orm感到困惑
SELECT count(*),
concat(date_part('month', issue_date), '/', date_part('year', issue_date) ) as date
FROM affiliates_issuelog
WHERE tenant_id = '{tenant_id}'
GROUP BY date_part('month', issue_date),
date_part('year', issue_date)
ORDER BY date_part('year', issue_date) desc,
date_part('month', issue_date) desc
我有一个按日期和机构(租户)记录新分支机构插入的模型,只需要从查询中接收一年中每月插入的记录总数,在此之前我一直使用Listview来制作页面,但我不知道如何使用ORM来过滤这些数据。
class IssueLog():
tenant = models.ForeignKey("tenants.Federation", on_delete=models.CASCADE)
issue_date = models.DateField(
default=date.today, verbose_name=_("date of issue")
)
class Meta:
verbose_name = _("Entrada de emissão")
verbose_name_plural = _("Entradas de emissão")
def __str__(self):
return f"{self.institution}, {self.tenant}"
我的页面返回了我在下面的示例中所做的数据列表,是否可以通过get_queryset()传递我想要的数据?我已经设法使用原始查询解决了我的问题,但该项目仅使用orm完成,所以为了团队的利益,我希望保留该模式。例如:
class AffiliateExpiredListView(HasRoleMixin, AffiliateFilterMxin, ListView):
allowed_roles = "federation"
model = Affiliate
ordering = "-created_at"
template_name_suffix = "issued_list_expired"
paginate_by = 20
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["renew_form"] = AffiliateRenewForm()
tenant_t = self.request.user.tenant
context["cancel_presets"] = tenant_t.cancelationreason_set.all()
return context
def get_queryset(self):
return super().get_queryset().filter(is_expired=True).order_by('full_name')
推荐答案
查询方式:
from django.db.models import Count
from django.db.models.functions import ExtractMonth, ExtractYear
IssueLog.objects.values(
year=ExtractYear('issue_date'),
month=ExtractMonth('issue_date')
).annotate(
total=Count('pk')
).order_by('-year', '-month')
这将创建一个带有如下字典的查询集:
<QuerySet [
{'year': 2022, 'month': 2, 'total': 14},
{'year': 2022, 'month': 1, 'total': 25},
{'year': 2021, 'month': 12, 'total': 13}
]>
我不会在数据库查询中进行字符串格式化,而是在模板中进行格式化,依此类推。
但模型不能abstract = True
[Django-doc]:这意味着没有表,它只用于继承目的,以实现逻辑并在其他地方重用。
这篇关于将原始SQL查询转换为Django orm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文