简体   繁体   中英

How to convert this complex query to Django ORM equivalent

Models:

Items(models.Model):
    name = models.CharField(max_length=250, verbose_name="Item Name")
    created_date = models.DateTimeField(auto_now_add=True)


Accounts(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    url_tag = models.CharField(max_length=200)
    item = models.ForeignKey(Items, on_delete=models.CASCADE)


Comments(models.Model):
    item = models.ForeignKey(Items, on_delete=models.CASCADE, null=True)
    comment = models.TextField(null=True)
    url_tag = models.URLField(null=True)
    is_flagged = models.BooleanField(default=False, null=True)
    response_required = models.BooleanField(default=True)
    created_date = models.DateTimeField(auto_now_add=True)


Responses(models.Model):
    response = models.TextField()
    comment = models.ForeignKey(Comments, on_delete=models.CASCADE)
    created_date = models.DateTimeField(auto_now_add=True)

Sql Query:

select c.id as comment_id, c.created_date, c.is_flagged, c.response_required 
from comments as c 
left join responses as r on c.id = r.comment_id
inner join items as i on i.id = c.item_id and r.comment_id is null 
left join accounts as a on 
(a.item_id = c.item_id and lower(a.url_tag) = lower(c.url_tag)
where c.id in (12, 32, 42, 54) 
ORDER BY c.created_date desc, comment_id desc;

What I tried:

filters = {
    'id__in': [12, 32, 42, 54]
}

comment_objs = Comment.objects.filter(**filters)
.select_related('commentsresponses', 'item')
.order_by('-created_date', '-id')

I want to get list of comment objects after joining and applying filters.

Maybe we can use serializers here i don't know since I don't have much experience with django

If time complexity doesn't matter for you, You can use raw SQL query:

from django.db import connection
cursor = connection.cursor()
cursor.execute('''select c.id as comment_id, c.created_date, c.is_flagged, 
c.response_required 
from comments....''')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM