S
S
Sergey Nizhny Novgorod2017-03-24 02:05:04
Django
Sergey Nizhny Novgorod, 2017-03-24 02:05:04

How to correctly pass data from the model via json?

Hello.
There is a Chat2 model:

topic = models.CharField(...)
author = models.ForeignKey(...)
chatdate = models.DateTimeField(...)
chattext = models.TextField(...)

It is necessary to issue one chat on ajax request:
1) If you try to send it like this, then an error appears
def chat_ajax(request):
    if request.POST:
        model = Chat2.objects.get(id=20)

        json = {
            'model ': model, 
        }

        return JsonResponse(json, safe=False)

2) If you do this, then everything works.
def chat_ajax(request):
    if request.POST:
        model = Chat2.objects.get(id=20)

        json = {
            'topic ': model.topic, 
            'author  ': model.author , 
            'chatdate ': model.chatdate, 
            'chattext ': model.chattext, 
        }

        return JsonResponse(json, safe=False)

The question is how to do it right so that the first method transmits everything normally?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-03-24
@Terras

First, the model can be serialized .
Second, the model can be converted to a dictionary:

from django.forms.models import model_to_dict
model = Chat2.objects.get(id=20)
field_values = model_to_dict(model)

Finally, from the database, you can immediately select not an instance of the model, but a dictionary:
field_values = Chat2.objects.get(id=20).values()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question