Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validator for serializer field with source= kwargs #3844

Closed
xiaohanyu opened this issue Jan 20, 2016 · 8 comments
Closed

Validator for serializer field with source= kwargs #3844

xiaohanyu opened this issue Jan 20, 2016 · 8 comments

Comments

@xiaohanyu
Copy link
Contributor

I've drafted a API with DRF, and there're two models, django.contrib.auth.models.User and Customer, code for Customer model:

from django.db import models
from django.contrib.auth.models import User


class Customer(models.Model):
    SEXES = (
        ('Male', 'Male'),
        ('Female', 'Female'),
    )

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    sex = models.CharField(max_length=10, choices=SEXES)
    mobile_number = models.CharField(max_length=20, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return u'<%s, %s, %s>' % (self.user.username, self.sex,
                                  self.mobile_number)

Note that Customer has a user = models.OneToOneField(User, on_delete=models.CASCADE) field, thus we can still use django's built authentication while add some extra field to our own Customer model.

The code for CustomerSerializer:

class CustomerSerializer(serializers.HyperlinkedModelSerializer):
    created_at = serializers.DateTimeField(read_only=True,
                                           format='%Y-%m-%dT%H:%M:%SZ')
    updated_at = serializers.DateTimeField(read_only=True,
                                           format='%Y-%m-%dT%H:%M:%SZ')
    mobile_number = serializers.CharField(min_length=6, max_length=20,
                validators=[UniqueValidator(queryset=Customer.objects.all())])
    username = serializers.CharField(source='user.username',
                validators=[UniqueValidator(queryset=User.objects.all())])
    email = serializers.CharField(source='user.email')
    first_name = serializers.CharField(source='user.first_name')
    last_name = serializers.CharField(source='user.last_name')
    password = serializers.CharField(source='user.password',
                                     min_length=6, max_length=32,
                                     write_only=True)

    ...

But when I work with CustomerSerializer, it will raise an exception:

E                   FieldError: Cannot resolve keyword u'user' into field. Choices are: auth_token, customer, date_joined, email, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, masseuse, password, user_permissions, username

I've checked DRF's code, and I think this exception comes from https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/validators.py#L38

        self.field_name = serializer_field.source_attrs[0]

I've read DRF's documentation: http://www.django-rest-framework.org/api-guide/fields/, it says

source
The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email').

And for EmailField(source='user.email'), the code self.field_name = serializer_field.source_attrs[0] will return user instead of email, which is not right and will lead to a FieldError.

For my case,

    username = serializers.CharField(source='user.username',
                validators=[UniqueValidator(queryset=User.objects.all())])

I think it's better to change self.field_name = serializer_field.source_attrs[0] to self.field_name = serializer_field.source_attrs[-1].

@xiaohanyu
Copy link
Contributor Author

Oh, seems I've forgot to add regression test.

Let's first discuss on this. If this is right, I'll add the necessary regression test.

@xordoquy
Copy link
Collaborator

Hi, looks like it's an issue in your code since you're not serializing the Customer instance.

@xiaohanyu
Copy link
Contributor Author

@xordoquy I think it's not an issue of my code.

Actually, I've changed the code as I posted here, and all tests passed. The logic for the code:

username = serializers.CharField(source='user.username',
                validators=[UniqueValidator(queryset=User.objects.all())])
  • username comes from a OneToOneField, namely, user.username
  • we should validate that the username is unique in User.objects.all()
  • however, with the current action of DRF's self.field_name = serializer_field.source_attrs[0], we get user, the table name, instead of username, the field name.
  • self.field_name = serializer_field.source_attrs[-1] will work for both case.

@xordoquy
Copy link
Collaborator

If you think it's really a DRF bug the next step would be to write a failing test case we could discuss.
I've been using the source in a couple of projects and it was working well so I'm a bit confused about why it doesn't work for you.

@cserra10
Copy link

I have the same issue. It only occurs when implementing the UniqueValidator. Any ideas of resolving without hardcode drf¡

@xiaohanyu
Copy link
Contributor Author

@Cesaringo Perhaps cherry-pick my closed rejected PR?

@xiaohanyu
Copy link
Contributor Author

@Cesaringo Spent two hours, added a regression testcase, take some time to help me review this patch?

xordoquy added a commit that referenced this issue May 26, 2016
…r-with-related-field

Fix #3844, refine validator for fields with <source=> kwargs
@nqryn
Copy link

nqryn commented Jan 6, 2017

@Cesaringo @xiaohanyu
I just ran into a related problem myself. The problem is that, using the models from above, when one tries to update a Customer instance, it WILL throw an error, because it tries to exclude the current instance obtained with the pk of the Customer from the User objects.

Is this intended behaviour ? I think it shouldn't be, but I'm looking forward to hear from you.
Here is a small piece of code for you to understand better :

CustomerView(generics.GenericAPIView, mixins.RetrieveModelMixin, mixins.UpdateModelMixin):
    serializer_class = CustomerSerializer

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def patch(self, request, *args, **kwargs):
        return self.partial_update(request, *args, **kwargs)
urlpatterns += [
...
url(r'^customers/(?P<pk>[0-9]+)/$', views.CustomerView.as_view()),
...

Say we have a Customer instance with pk 127, and its corresponding User instance has pk 165.
When trying to update the Customer on URL customers/127/ using the same username that it originally had, it will exclude from the queryset the User instance with pk 127, resulting in an error.

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants