Home > Net >  Conversion of “where exists” SQL clause to Django ORM
Conversion of “where exists” SQL clause to Django ORM

Time:10-08

I want to convert below PostgreSQL query into Django ORM. It would be great if someone can help me out here.

Query:

select U0.*
from audit_audithistory U0
where exists
(
select U2.historyId
from (select Max(U1.id) as historyId
from audit_audithistory U1
group by U1.group_uid, U1.record_identifier
) U2
where U0.id = U2.historyId
)

Model:

class AuditHistory(models.Model):
    model_name = models.ForeignKey(AuditHistoryConfigMaster, on_delete=models.CASCADE)
    record_identifier = models.JSONField(blank=False, default=dict)
    tenant_id = models.CharField(null=True, blank=True, max_length=500, verbose_name='Application Tenant ID')
    updated_fields = models.JSONField(blank=True, default=dict, verbose_name='Complete Current Record')
    modified_by = models.CharField(max_length=200, blank=False, null=False)
    group_uid = models.CharField(max_length=50, blank=False, null=False)
    created_dtm = models.DateTimeField(auto_now_add=True, blank=False, null=False)
    update_dtm = models.DateTimeField(auto_now=True, blank=False, null=False)

CodePudding user response:

you can read about:

from django.db.models import Exists, OuterRef

example:

var_name = ModelName.objects.annotate(
Any_name_you_want=Exists(ModelName.objects.filter(FieldName=OuterRef('field_name'), user=request.user)))
  • Related