[4.2.x] Fixed #34779 -- Avoided unnecessary selection of non-nullable m2m fields without natural keys during serialization.

By using `select_related(None)` instead of `select_related()`, the
unnecessary joins are completely avoided. Note that the current tests
already covers the change, when the field is not `null=True`.

Regression in f9936deed1.

Backport of 517d3bb4dd from main
This commit is contained in:
Juan Alvarez 2023-08-15 16:53:30 -03:00 committed by Mariusz Felisiak
parent d34db6602e
commit 46b2b08e45
4 changed files with 13 additions and 3 deletions

View File

@ -80,7 +80,10 @@ class Serializer(base.Serializer):
def queryset_iterator(obj, field):
return (
getattr(obj, field.name).select_related().only("pk").iterator()
getattr(obj, field.name)
.select_related(None)
.only("pk")
.iterator()
)
m2m_iter = getattr(obj, "_prefetched_objects_cache", {}).get(

View File

@ -156,7 +156,10 @@ class Serializer(base.Serializer):
def queryset_iterator(obj, field):
return (
getattr(obj, field.name).select_related().only("pk").iterator()
getattr(obj, field.name)
.select_related(None)
.only("pk")
.iterator()
)
m2m_iter = getattr(obj, "_prefetched_objects_cache", {}).get(

View File

@ -16,3 +16,7 @@ Bugfixes
* Fixed a bug in Django 4.2 where the deprecated ``DEFAULT_FILE_STORAGE`` and
``STATICFILES_STORAGE`` settings were not synced with ``STORAGES``
(:ticket:`34773`).
* Fixed a regression in Django 4.2.2 that caused an unnecessary selection of a
non-nullable ``ManyToManyField`` without a natural key during serialization
(:ticket:`34779`).

View File

@ -60,7 +60,7 @@ class TopicManager(models.Manager):
class Topic(models.Model):
name = models.CharField(max_length=255)
category = models.ForeignKey(Category, models.CASCADE, null=True)
category = models.ForeignKey(Category, models.CASCADE)
objects = TopicManager()