0

I have following cutsom base Serializer:

class CustombBaseSerializer(Serializer):

    def get_object(self, model, **kwargs):
        try:
            return model.objects.get(**kwargs)   
        except model.DoesNotExist:
            raise ValidationError(
                f"{model._meta.verbose_name.title()} Does Not Exist."
            )

and following serializer inherited from CutsomBaseSerializer (above):

class TextAnswerSerializer(CustombBaseSerializer):
    sheet_code = CharField(
        max_length=11,
    )

    def validate_sheet_code(self, value):
        return self.get_object(SheetCode, pk=value)

    def validate(self, attrs):
        if attrs.get('sheet_code').user_id != attrs.get('user_id'):
            raise ValidationError("It's not yours!")

        if attrs.get('sheet_code').kind == 'infinity':
            # some stuff
        elif attrs.get('sheet_code').kind == 'feedback':
            # some more stuff
        else:
            # some other stuff

        return attrs

when I send data to this serializer, it raises an exception:

myapp.models.SheetCode.MultipleObjectsReturned: get() returned more than one SheetCode -- it returned 3!

I find that, the validate_sheet_code triggered 3 times. what's the problem? and how to fix it?

Update
I changed the validate_sheet_code as follows, but it raises previous error again:

def validate_sheet_code(self, value):
    try:
        return SheetCode.objects.get(pk=value)
    except SheetCode.DoesNotExist:
        raise ValidationError()

it raises that error again.

msln
  • 1,318
  • 2
  • 19
  • 38
  • `validate_sheet_code` returned 3 objects. `get_objects` should return 1 object but here it returned 3. – Nalin Dobhal Jul 30 '19 at 08:51
  • @NalinDobhal I tried to track error. `validate_sheet_code` triggered 3 times. `get_object` returns one. or maybe `get_object` triggered 3 times. but why? – msln Jul 30 '19 at 09:11
  • the validate method may be called several times likely due to the debug informations from your initial error (`get() returned more than one SheetCode -- it returned 3!`). Fix the error first and then see how many times the validate method is called. – Linovia Jul 30 '19 at 11:55

0 Answers0