Skip to content

Fix UniqueForDateValidator required error on update with auto_now_add - #10096

Closed
mahdirahimi1999 wants to merge 1 commit into
encode:mainfrom
mahdirahimi1999:fix/unique-for-date-update-auto-now-add
Closed

mahdirahimi1999 wants to merge 1 commit into
encode:mainfrom
mahdirahimi1999:fix/unique-for-date-update-auto-now-add

Conversation

@mahdirahimi1999

@mahdirahimi1999 mahdirahimi1999 commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

I ran into this while working on an API that uses unique_for_date with auto_now_add on the date field. Creating a record worked. Updating it didn't — even a full PUT came back with published: This field is required, and the client isn't supposed to send that field at all.

Say you have:

class Article(models.Model):
    slug = models.CharField(max_length=100, unique_for_date='published')
    published = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=200)

ModelSerializer with fields = ('id', 'slug', 'title') wires up a HiddenField(default=CreateOnlyDefault(...)) plus UniqueForDateValidator. POST is fine. Then:

PUT /articles/1/
{"slug": "hello", "title": "Updated"}

CreateOnlyDefault raises SkipField on update, so published never lands in attrs. 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.

UniqueTogetherValidator already skips the required check when serializer.instance is 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_value keys by source, not the serializer field name. The old check was if field_name not in attrs, so something like name = CharField(source='slug') could miss the value even on create. It now looks at serializer.fields[name].source, and on update copies the instance value onto that source key.

PATCH hits the same thing because HiddenField is skipped when partial=True (looks like #6341).

Added tests for the hidden auto_now_add path, the read_only date field, and partial updates.

Fixes #6341

@ege-arhan ege-arhan left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking closely at the proposed changes in rest_framework/validators.py:

  1. attrs[self.field] lookup in filter_queryset:
    If a serializer field specifies a custom source (e.g. headline = serializers.CharField(source="title")), the validated data dict populated by DRF uses source ("title"), not the serializer field name ("headline").
    filter_queryset assumes self.field is a key in attrs:
value = attrs[self.field]

When source != self.field, this raises KeyError: 'headline'. UniqueTogetherValidator handles this by resolving source_attrs across attrs.

  1. to_internal_value on 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.

  1. 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')]}

@auvipy auvipy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

closing as duplicate of #10040

@auvipy auvipy closed this Nov 7, 2026
@mahdirahimi1999
mahdirahimi1999 deleted the fix/unique-for-date-update-auto-now-add branch November 7, 2026 11:22
@mahdirahimi1999
mahdirahimi1999 restored the fix/unique-for-date-update-auto-now-add branch November 7, 2026 11:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Model unique_for_month changes ability to partially update ModelSerializer

3 participants