Answer the question
In order to leave comments, you need to log in
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(...)
def chat_ajax(request):
if request.POST:
model = Chat2.objects.get(id=20)
json = {
'model ': model,
}
return JsonResponse(json, safe=False)
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)
Answer the question
In order to leave comments, you need to log in
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)
field_values = Chat2.objects.get(id=20).values()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question