djangodjango-ormdjango-databasedjango-database-functions

Django bulk update with data two tables over


I want to bulk update a table with data two tables over. A solution has been given for the simpler case mentioned in the documentation of:

Entry.objects.update(headline=F('blog__name'))

For that solution, see

https://stackoverflow.com/a/50561753/1092940

Expanding from the example, imagine that Entry has a Foreign Key reference to Blog via a field named blog, and that Blog has a Foreign Key reference to User via a field named author. I want the equivalent of:

Entry.objects.update(author_name=F('blog__author__username'))

As in the prior solution, the solution is expected to employ SubQuery and OuterRef.

The reason I ask here is because I lack confidence where this problem starts to employ multiple OuterRefs, and confusion arises about which outer ref it refers to.


Solution

  • The reason I ask here is because I lack confidence where this problem starts to employ multiple OuterRefs, and confusion arises about which outer ref it refers to.

    It does not require multiple outer references, you can update with:

    from django.db.models import OuterRef, Subquery
    
    author_name = Author.objects.filter(
        blogs__id=OuterRef('blog_id')
    ).values_list(
        'username'
    )[:1]
    
    Entry.objects.update(
        author_name=Subquery(author_name)
    )

    You here thus specify that you look for an Author with a related Blog with an id equal to the blog_id of the Entry.