Django update queryset with annotation

前端 未结 6 585
梦谈多话
梦谈多话 2020-12-24 01:06

I want to update all rows in queryset by using annotated value.

I have a simple models:

class Relation(models.Model):
    rating = models.IntegerFiel         


        
6条回答
  •  自闭症患者
    2020-12-24 01:49

    For Django 1.11+ you can use Subquery:

    from django.db.models import OuterRef, Subquery, Sum
    
    Relation.objects.update(
        rating=Subquery(
            Relation.objects.filter(
                id=OuterRef('id')
            ).annotate(
                total_rating=Sum('sign_relations__rating')
            ).values('total_rating')[:1]
        )
    )
    

    This code produce the same SQL code proposed by Tomasz Jakub Rup but with no use of RawSQL expression. The Django documentation warns against the use of RawSQL due to the possibility of SQL injection).

    Update

    I published an article based on this answer with more in-depth explanations: Updating a Django queryset with annotation and subquery on paulox.net

提交回复
热议问题