Search code examples
pythonpython-3.xdjangodjango-3.1

Use of Subquery on django's update


I'm currently getting this error

Joined field references are not permitted in this query

Any idea why it happens if I do this? (models recreated into a simpler version)

class Foo(models.Model):
    bar = models.ForeignKey(
       Bar, related_name='foos', on_delete=models.CASCADE)
    baz = models.ForeignKey(
       Baz, related_name='foos', null=True, blank=True,
       on_delete=models.SET_NULL)

class Bar(models.Model):
    name = models.CharField(max_length=255)

class Baz(models.Model):
    name = models.CharField(max_length=255)

I wanted to update the baz field of all Foo instances based on all Baz with the same name of Foo's bar

Foo.objects.update(
    baz=Subquery(
        Baz.objects.filter(
            name=OuterRef('bar__name')
        ).values('pk')[:1]
    )
)

Solution

  • I made it work by accessing it through Bar's model and chaining OuterRef

    Foo.objects.update(
        baz=Subquery(
            Baz.objects.filter(
                name=Subquery(
                    Bar.objects.filter(
                        pk=OuterRef(OuterRef('bar_id'))
                    ).values('name')[:1]
                )
            ).values('pk')[:1]
        )
    )