OneToOneField testing for uniqueness

14 views
Skip to first unread message

David

unread,
Sep 19, 2017, 7:40:18 AM9/19/17
to Django REST framework
Hi

I have a model such as:

class TestObj(models.Model):
    owner = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)


My serializer is like:

class TestObjSerializer(serializers.HyperlinkedModelSerializer):
     class Meta:
          Model = TestObj
          fields = ('name')

I have 2 issues.

Firstly, and most importantly, there must only be one TestObj per owner. Hence the OneToOneField. When I save currently, I get a postgres duplication violation error. I need to have my serializer return a validation error. How can I achieve this please? Should it be in my perform_create and perform_update methods? Or should it be in the serializer itself?

Secondly, if the validation takes place in the serializer, at no point do I want to expose the user in my API so therefor don't want to add it to fields = () Is that possible?

Many thanks

David

unread,
Sep 19, 2017, 7:47:08 AM9/19/17
to Django REST framework
I had scoured the docs a lot, but typically having posted this found the answer straight away.

def perform_create(self, serializer):
    queryset = SignupRequest.objects.filter(user=self.request.user)
    if queryset.exists():
        raise ValidationError('You have already signed up')
    serializer.save(user=self.request.user)
Reply all
Reply to author
Forward
0 new messages