簡體   English   中英

如何將此復雜查詢轉換為等效的 Django ORM

[英]How to convert this complex query to Django ORM equivalent

楷模:

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)

查詢:

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;

我試過的:

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

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

我想在加入和應用過濾器后獲取評論對象列表。

也許我們可以在這里使用序列化程序,我不知道,因為我對 django 沒有太多經驗

如果時間復雜度對您來說無關緊要,您可以使用原始 SQL 查詢:

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....''')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM