# Update model using subquery with reference to outer fields

**URL:** <https://forum.djangoproject.com/t/update-model-using-subquery-with-reference-to-outer-fields/17265>\
**Category:** Using the ORM\
**Created:** [November 25, 2022, 11:14am UTC](https://forum.djangoproject.com/t/update-model-using-subquery-with-reference-to-outer-fields/17265 "2022-11-25T11:14:12Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![elias](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/elias/32/11042_2.png) [@elias](https://forum.djangoproject.com/u/elias)\
**Post date:** [November 25, 2022, 11:14am UTC](https://forum.djangoproject.com/t/update-model-using-subquery-with-reference-to-outer-fields/17265/1 "2022-11-25T11:14:12Z")

</div>

Hi,

I was wondering whether it is possible to rewrite a for loop to update a model.

So I have models which are (simplified) like this:

```auto
class Text(Model):
    key = CharField(primary_key=True, max_length=100)
    part_of_journal = ForeignKey(Journal, null=True, on_delete=CASCADE)

class Journal(Model):
    identifier = CharField(primary_key=True, max_length=100)

```

Both `key` and `identifier` are similar but not the same. Now I want to assign the Text to the right Journal. It’s possible in a for loop using

```auto
for text in Text.objects.all():
    text.part_of_journal = Journal.objects.filter(identifier='streams/' + text.key[:4]).first()
    text.save()

```

I was wondering whether it is possible to do the same using an update with a subquery like:

```auto
Text.objects.all()\
            .annotate(converted_key=Concat(V('streams/'), Substr('key', 1, 5)))\
            .update(part_of_journal=Journal.objects.filter(identifier=OuterRef('converted_key')).first())

```

However, all the different versions I’ve tried always fail with referencing the `converted_key`.

Does anyone know whether/how that is possible?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 25, 2022, 12:48pm UTC](https://forum.djangoproject.com/t/update-model-using-subquery-with-reference-to-outer-fields/17265/2 "2022-11-25T12:48:00Z")

</div>

Is it possible? No, not this way.

The `update` function applies to a queryset, it does not create individual updates for each row. (See the docs at [Updating multiple objects at once](https://docs.djangoproject.com/en/4.1/topics/db/queries/#updating-multiple-objects-at-once) for specifics on the limitations of the `update` function.)

If you’re looking to reduce the number of saves being performed, you may find [`bulk_update`](https://docs.djangoproject.com/en/4.1/ref/models/querysets/#bulk-update) helpful. You’re still going to iterate over the objects, but only issuing one command to perform the save.

---

<div class="post-metadata">

**Author:** ![CodenameTim](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/codenametim/32/31507_2.png) [@CodenameTim](https://forum.djangoproject.com/u/CodenameTim)\
**Post date:** [November 25, 2022, 1:37pm UTC](https://forum.djangoproject.com/t/update-model-using-subquery-with-reference-to-outer-fields/17265/3 "2022-11-25T13:37:16Z")

</div>

I would have thought this was possible. There’d be a annotate that has a subquery on Journal that does the lookup using the identifier comparison, but it returns the id. Then the update uses F(“annotated\_journal\_id”) for the value.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 25, 2022, 1:56pm UTC](https://forum.djangoproject.com/t/update-model-using-subquery-with-reference-to-outer-fields/17265/4 "2022-11-25T13:56:18Z")

</div>

Yep, that works! (Just checked it)

Move the Journal query to the annotation to create the new value and then use the update to update based upon the annotated value.

---

<div class="post-metadata">

**Author:** ![elias](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/elias/32/11042_2.png) [@elias](https://forum.djangoproject.com/u/elias)\
**Post date:** [November 25, 2022, 2:05pm UTC](https://forum.djangoproject.com/t/update-model-using-subquery-with-reference-to-outer-fields/17265/5 "2022-11-25T14:05:42Z")

</div>

Thanks for the replies!

I actually just figured out another way to do this: Not using `annotate` at all but using a `Subquery` with `OuterRef(key)` as part of the `update` function.

This was an interesting deep-dive into the django ORM

---

<div class="post-metadata">

**Author:** ![CodenameTim](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/codenametim/32/31507_2.png) [@CodenameTim](https://forum.djangoproject.com/u/CodenameTim)\
**Post date:** [November 25, 2022, 2:18pm UTC](https://forum.djangoproject.com/t/update-model-using-subquery-with-reference-to-outer-fields/17265/6 "2022-11-25T14:18:55Z")

</div>

I didn’t know that was possible, TIL!

---

<div class="post-metadata">

**Author:** ![speno](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/speno/32/179_2.png) [@speno](https://forum.djangoproject.com/u/speno)\
**Post date:** [November 25, 2022, 3:46pm UTC](https://forum.djangoproject.com/t/update-model-using-subquery-with-reference-to-outer-fields/17265/7 "2022-11-25T15:46:07Z")

</div>

Can you show what that looks like using your example models please? Thanks.

---

<div class="post-metadata">

**Author:** ![elias](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/elias/32/11042_2.png) [@elias](https://forum.djangoproject.com/u/elias)\
**Post date:** [November 28, 2022, 10:51am UTC](https://forum.djangoproject.com/t/update-model-using-subquery-with-reference-to-outer-fields/17265/8 "2022-11-28T10:51:03Z")

</div>

Sure, this is what I ended up with:

```auto
subquery = Journal.objects.filter(
    identifier=Concat(V('streams/'), Substr(OuterRef('key'), 1, 5))
)
Text.objects.update(
    part_of_journal=Subquery(
        subquery.values('identifier')[:1],
        output_field=models.CharField()
    )
)

```
