Repository navigation
Fix UniqueForDateValidator required error on update with auto_now_add - #10096
mahdirahimi1999 wants to merge 1 commit into
Conversation
ege-arhan
left a comment
There was a problem hiding this comment.
Looking closely at the proposed changes in rest_framework/validators.py:
attrs[self.field]lookup infilter_queryset:
If a serializer field specifies a customsource(e.g.headline = serializers.CharField(source="title")), the validated data dict populated by DRF usessource("title"), not the serializer field name ("headline").
filter_querysetassumesself.fieldis a key inattrs:
value = attrs[self.field]When source != self.field, this raises KeyError: 'headline'. UniqueTogetherValidator handles this by resolving source_attrs across attrs.
to_internal_valueon existing instance attributes during partial update:
if not isinstance(value, date):
value = serializer.fields[name].to_internal_value(value)When self.field is a ForeignKey (represented by PrimaryKeyRelatedField on the serializer), getattr(serializer.instance, source) returns the related model instance (e.g., an Author object), not the primitive primary key.
Calling to_internal_value(author_instance) on PrimaryKeyRelatedField raises:
ValidationError: Incorrect type. Expected pk value, received Author.
In UniqueTogetherValidator, the validator extracts the PK directly from the instance or skips re-running to_internal_value when the value is already a model instance.
- Serializer fields lookup when date field is omitted from serializer:
field_name = serializer.fields[self.field].source_attrs[-1]
date_field_name = serializer.fields[self.date_field].source_attrs[-1]If date_field is not declared as a field on the serializer (e.g., when published is managed purely at model level or marked read-only outside the serializer), indexing serializer.fields[self.date_field] raises KeyError.
Here is a minimal repro demonstrating (1) and (2):
from datetime import date
from django.db import connection, models
from rest_framework import serializers
from rest_framework.validators import UniqueForDateValidator
class Author(models.Model):
name = models.CharField(max_length=50)
class Meta:
app_label = "repro"
class Post(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE, unique_for_date="published")
published = models.DateField()
body = models.CharField(max_length=100)
class Meta:
app_label = "repro"
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ("id", "author", "published", "body")
# Partial update with an existing instance
author = Author.objects.create(name="Jane")
post = Post.objects.create(author=author, published=date(2026, 11, 7), body="Hello")
s = PostSerializer(instance=post, data={"body": "Updated"}, partial=True)
s.is_valid()
# s.errors -> {'non_field_errors': [ErrorDetail(string='Incorrect type. Expected pk value, received Author.', code='incorrect_type')]}
I ran into this while working on an API that uses
unique_for_datewithauto_now_addon the date field. Creating a record worked. Updating it didn't — even a full PUT came back withpublished: This field is required, and the client isn't supposed to send that field at all.Say you have:
ModelSerializerwithfields = ('id', 'slug', 'title')wires up aHiddenField(default=CreateOnlyDefault(...))plusUniqueForDateValidator. POST is fine. Then:CreateOnlyDefaultraisesSkipFieldon update, sopublishednever lands inattrs. The validator still treats it as required and you get 400. Django's own save is happy with that update — it's only DRF uniqueness that blows up.UniqueTogetherValidatoralready skips the required check whenserializer.instanceis set and fills missing values from the instance. This does the same for the UniqueFor* validators.Also aligned the attrs lookup with UniqueTogether:
to_internal_valuekeys bysource, not the serializer field name. The old check wasif field_name not in attrs, so something likename = CharField(source='slug')could miss the value even on create. It now looks atserializer.fields[name].source, and on update copies the instance value onto that source key.PATCH hits the same thing because
HiddenFieldis skipped whenpartial=True(looks like #6341).Added tests for the hidden
auto_now_addpath, the read_only date field, and partial updates.Fixes #6341