N
N
NikClik2018-10-26 13:36:59
Django
NikClik, 2018-10-26 13:36:59

How to form a key-value relationship in a __str__ model?

I’ll start from the farthest, I’m writing a client-server application, in it, let’s say there are 2 models, a record and actions on a record (the example is taken conditionally, I know that you can organize a record of actions on a record in a different way)
wrote an api, wrote a Serializer for the model And when I send a request, I get something like this:

[
    {
        "Запись.ключ1": "Значение",
        "Запись.ключ2": "Значение",
        "Запись.ключ3": "Значение",
        "Запись.ключ4": "Значение",
        "Действия": [
            "Значение 1: Значение 2 Значение 3 Значение 4",
            "Значение 1: Значение 2 Значение 3 Значение 4",
            "Значение 1: Значение 2 Значение 3 Значение 4"
        ]
    }
]

The bottom line is that the string that is returned from the "Actions" model is written in the __str__ model, is it possible to somehow write in the __str__ method so that everything is returned from the "Actions" model in the form:
"Действия": [
        {
            "Действие.ключ1" : "Значение1",
            "Действие.ключ2" : "Значение2",
            "Действие.ключ3" : "Значение3",
        },
        {
            "Действие.ключ1" : "Значение1",
            "Действие.ключ2" : "Значение2",
            "Действие.ключ3" : "Значение3",
        },
]

and if not, how can I arrange for the data to be transmitted exactly the way I want?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2018-10-26
@vintello

__str__ is the formation of a textual representation of the class for insertion into the log or into the debugger, for example,
you just need to check the type of the subordinate object, and if it is one of the list of possible subordinate classes, then call the toJSON() method for it, for example. Naturally, in subordinate classes, this method must be implemented

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question