mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-06 21:40:13 +03:00
fix in UniqueTogetherValidator to allow it to handle querysets
this is especially important when using a serializer with many=True and the model having unique multiple constrains
This commit is contained in:
parent
4f1506c77e
commit
83d5da54ca
|
@ -7,6 +7,7 @@ object creation, and makes it possible to switch between using the implicit
|
||||||
`ModelSerializer` class and an equivalent explicit `Serializer` class.
|
`ModelSerializer` class and an equivalent explicit `Serializer` class.
|
||||||
"""
|
"""
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
from django.db import models
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
from rest_framework.compat import unicode_to_repr
|
from rest_framework.compat import unicode_to_repr
|
||||||
from rest_framework.exceptions import ValidationError
|
from rest_framework.exceptions import ValidationError
|
||||||
|
@ -112,7 +113,7 @@ class UniqueTogetherValidator:
|
||||||
"""
|
"""
|
||||||
# If this is an update, then any unprovided field should
|
# If this is an update, then any unprovided field should
|
||||||
# have it's value set based on the existing instance attribute.
|
# have it's value set based on the existing instance attribute.
|
||||||
if self.instance is not None:
|
if self.instance is not None and isinstance(self.instance, models.Model):
|
||||||
for field_name in self.fields:
|
for field_name in self.fields:
|
||||||
if field_name not in attrs:
|
if field_name not in attrs:
|
||||||
attrs[field_name] = getattr(self.instance, field_name)
|
attrs[field_name] = getattr(self.instance, field_name)
|
||||||
|
@ -121,6 +122,7 @@ class UniqueTogetherValidator:
|
||||||
filter_kwargs = dict([
|
filter_kwargs = dict([
|
||||||
(field_name, attrs[field_name])
|
(field_name, attrs[field_name])
|
||||||
for field_name in self.fields
|
for field_name in self.fields
|
||||||
|
if field_name in attrs
|
||||||
])
|
])
|
||||||
return queryset.filter(**filter_kwargs)
|
return queryset.filter(**filter_kwargs)
|
||||||
|
|
||||||
|
@ -130,7 +132,10 @@ class UniqueTogetherValidator:
|
||||||
that instance itself as a uniqueness conflict.
|
that instance itself as a uniqueness conflict.
|
||||||
"""
|
"""
|
||||||
if self.instance is not None:
|
if self.instance is not None:
|
||||||
return queryset.exclude(pk=self.instance.pk)
|
if isinstance(self.instance, models.QuerySet):
|
||||||
|
return queryset.exclude(pk__in=self.instance.values_list('pk', flat=True))
|
||||||
|
else:
|
||||||
|
return queryset.exclude(pk=self.instance.pk)
|
||||||
return queryset
|
return queryset
|
||||||
|
|
||||||
def __call__(self, attrs):
|
def __call__(self, attrs):
|
||||||
|
|
Loading…
Reference in New Issue
Block a user