Python-Django and JavaScript – Translating Between Them

djangojavascriptobject-orientedpython

I have a conceptual question about 'translating' between objects I have stored in Django (in Postgres) that I want to use on the front-end. So I have a user object in Python that holds basic things: an id, a username, a password. Let's say I want to output all of that information using Javascript on the client side. Can I just give JS a python object and it will make it into a JS object? I know JS is known for being 'fast and loose' with typing but that just seems absurd!

I'm not looking for syntax, but just an overview of how this would work. Can I put Python objects in AJAX requests, then translate them client side, or is this going to be a basic break-down-things-on-server-side, ship them off, and recombine them on the client side type of thing?

Best Answer

You can serialize the data in your Python objects easily and use this data in your Javascript code- as some other answers say, JSON for instance is a fairly multi-language way to represent data which has support for many languages- among them Javascript (JSON is really limited Javascript object literal syntax) and Python.

However, these approaches mostly deal with data. If your Python objects have "behaviour"- namely, they have methods with code, they will be "lost in translation".

Say if you have a Python class with a person's data (name, birth date) but with a method which calculates the person's age (now - birth date), if you encode an object of this class as JSON and use it in Javascript, you won't have the "age" method, you will have to reimplement it.

That is, most inter-language communication methods ship "data" not "objects and classes".

There are approaches that try to communicate "objects and classes"; see Java's RMI for instance, which lets you obtain references to remote objects and invoke methods remotely. However, these things get messy quick- for instance, different languages are well, different, and stuff cannot translate 100% accurately. Also, the semantics of remote method invocation are not trivial, and can rapidly become confusing.

Related Topic