← Back to Pull requests

fix(validators): guard UniqueConstraint validators against queryset instance in ListSerializer (fixes #9484) #10000

Closed
unknown closed this pull request without merging on Sep 06, 2026 07:57 UTC
View on GitHub
unknown unknown commented on Jul 21, 2026 16:50 UTC
Author

Problem

Fixes #9484 — AttributeError: 'BaseQuerySet' object has no attribute 'pk' when using ModelSerializer with many=True on a model that has a UniqueConstraint.

Root Cause

When many=True is passed to a ModelSerializer, many_init creates a ListSerializer wrapping the child serializer. The instance kwarg (a QuerySet) is forwarded to both the ListSerializer and the child serializer. When the child's UniqueTogetherValidator (or UniqueValidator) runs during validation, it calls:

def exclude_current_instance(self, attrs, queryset, instance):
    if instance is not None:
        return queryset.exclude(pk=instance.pk)  # 💥 QuerySet has no .pk
    return queryset

Because instance is the entire QuerySet, not a model instance, .pk raises AttributeError.

Reproducer (from #9484)

class Pet(models.Model):
    name = models.CharField(max_length=100)
    animal_type = models.CharField(max_length=100)
    can_fly = models.BooleanField(null=True)

    class Meta:
        constraints = [
            UniqueConstraint(fields=["name", "animal_type"], name="unique_pet")
        ]

class PetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Pet
        fields = ('name', 'animal_type', 'can_fly')

class PetListSerializer(serializers.ListSerializer):
    child = PetSerializer()

    def create(self, validated_data):
        return Pet.objects.bulk_create([Pet(**item) for item in validated_data])

new_data = [
    {"name": "Polly", "animal_type": "Parrot", "can_fly": True},
    {"name": "Penguin", "animal_type": "Bird", "can_fly": False},
]
serializer = PetListSerializer(Pet.objects.all(), data=new_data, many=True)
serializer.is_valid(raise_exception=True)  # AttributeError: 'BaseQuerySet' object has no attribute 'pk'

Fix

Introduces a small private helper _is_single_instance(instance) that returns True only if instance is a non-None, non-QuerySet, non-list object that has a .pk attribute. Both UniqueValidator.exclude_current_instance and UniqueTogetherValidator.exclude_current_instance (and BaseUniqueForValidator.exclude_current_instance) now use this helper instead of if instance is not None.

This is minimal and fully backward-compatible:

  • Single-instance update: unchanged — instance.pk still used to exclude the current object.

  • Bulk create (ListSerializer + queryset instance): validators no longer crash; treat each child item as a create.

  • None instance (plain create): unchanged.
  • The fix also corrects UniqueTogetherValidator.filter_queryset and __call__ which had the same latent bug of reading from serializer.instance without guarding against a queryset type.

    Checklist

  • Minimal, targeted fix (one helper, three call sites updated)

  • Backward compatible — no API changes

  • Fixes crash in UniqueValidator, UniqueTogetherValidator, and BaseUniqueForValidator

  • Covers the filter_queryset path in UniqueTogetherValidator (latent bug: getattr(serializer.instance, source) would also crash if instance is a queryset)
  • Diff: 391 lines (+293 / -98) across 4 files Reviewer: p-r-a-v-i-n Review duration: 67146m
    All Vouch review confidence checks passed
    Residual risk 0.17 = Change Risk (0.43) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.43 · 391 lines diff across 4 files
    0.43
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.357
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #10000"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 43.1% (MEDIUM) · Higher = larger blast radius
    43.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 17% · Safe to merge
    17%