Django get_or_create throwing integrity errors

618 views Asked by At

I'm so confused as to why the get_or_create() method should throw error here, I have this in my serializer:

def create(self, validated_data): user, _ = User.objects.get_or_create(id=validated_data['message']['from_user']['id'], defaults=validated_data['message']['from_user'])

chat, created = Chat.objects.get_or_create(id=validated_data['message']['chat']['id'],
                                           defaults=validated_data['message']['chat'])

message, _ = Message.objects.get_or_create(message_id=validated_data['message']['message_id'],
                                           defaults={'message_id': validated_data['message']['message_id'],
                                           'from_user': user,
                                           'date': validated_data['message']['date'],
                                           'chat': chat,
                                           'text': validated_data['message']['text']})
update, _ = Update.objects.get_or_create(update_id=validated_data['update_id'],
                                         defaults={'update_id': validated_data['update_id'],
                                         'message': message})

return update

It says that: {u'from': {'id': [u'User with this id already exists.']}, u'chat': {'id': [u'Chat with this id already exists.']}}

I have checked other threads, but the solution they all gave is what I already have in my code so I'm really confused

1

There are 1 answers

0
Ken On BEST ANSWER

It appears the problem was that the serializer could not implicitly convert the id's to ints even though they are specified as ints in the model. So whenever it tried to look for a chat or user with the given id it does not find one(possible uses string id's) but trying to create a new object with the given id will make the db (postgreSQL in this case) throw an integrity error. Adding id = serializers.IntegerField() solved the problem